lib/PDL/Primitive.pm

filter: Statementstmt 100% 14 / 14 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 3 / 3 Podpod n/a totaltotal 100% 17 / 17 CC 1 SCAR 0.0
CC
1
Cov
100%
BEGIN
1.0
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« lib/PDL/PP.pm ↑ Summary lib/PDL/Slices.pm »
1 #
2 # GENERATED WITH PDL::PP from lib/PDL/Primitive.pd! Don't modify!
3 #
4 package PDL::Primitive;
5  
6 71 our @EXPORT_OK = qw(inner outer matmult innerwt inner2 inner2d inner2t crossp norm indadd conv1d in uniq uniqind uniqvec hclip lclip clip wtstat statsover stats histogram whistogram histogram2d whistogram2d fibonacci append axisvalues cmpvec eqvec enumvec enumvecg vsearchvec unionvec intersectvec setdiffvec union_sorted intersect_sorted setdiff_sorted vcos srandom random randsym grandom vsearch vsearch_sample vsearch_insert_leftmost vsearch_insert_rightmost vsearch_match vsearch_bin_inclusive vsearch_bin_exclusive interpolate interpol interpND one2nd which which_both whichover approx_artol where where_both whereND whereND_both whichND whichND_both setops intersect pchip_chim pchip_chic pchip_chsp pchip_chfd pchip_chfe pchip_chia pchip_chid pchip_chbs pchip_bvalu );
7 71 our %EXPORT_TAGS = (Func=>\@EXPORT_OK);
8  
9 71 ▶use PDL::Core;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 71 ▶use PDL::Exporter;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 71 ▶use DynaLoader;
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13  
14
15 71 our @ISA = ( 'PDL::Exporter','DynaLoader' );
16 71 push @PDL::Core::PP, __PACKAGE__;
17 71 bootstrap PDL::Primitive ;
18  
19 { package # hide from MetaCPAN
20 PDL;
21  
22 #line 1445 "lib/PDL/PP.pm"
23 {
24 my ($foo, $overload_sub);
25 sub overload_matmult {
26 Carp::confess("PDL::matmult: overloaded 'x' given undef")
27 if grep !defined, @_[0,1];
28 return PDL::matmult(@_) unless ref $_[1]
29 && (ref $_[1] ne 'PDL')
30 && defined($foo = overload::Method($_[1], 'x'))
31 && $foo != $overload_sub; # recursion guard
32 goto &$foo;
33 }
34 use overload 'x' => $overload_sub = \&overload_matmult;
35 }
36 #line 37 "lib/PDL/Primitive.pm"
37 }
38  
39  
40  
41  
42  
43  
44  
45 #line 12 "lib/PDL/Primitive.pd"
46  
47 use strict;
48 use warnings;
49 use PDL::Slices;
50 use Carp;
51  
52 =head1 NAME
53  
54 PDL::Primitive - primitive operations for pdl
55  
56 =head1 DESCRIPTION
57  
58 This module provides some primitive and useful functions defined
59 using PDL::PP and able to use the new indexing tricks.
60  
61 See L<PDL::Indexing> for how to use indices creatively.
62 For explanation of the signature format, see L<PDL::PP>.
63  
64 =head1 SYNOPSIS
65  
66 # Pulls in PDL::Primitive, among other modules.
67 use PDL;
68  
69 # Only pull in PDL::Primitive:
70 use PDL::Primitive;
71  
72 =cut
73 #line 74 "lib/PDL/Primitive.pm"
74  
75  
76 =head1 FUNCTIONS
77  
78 =cut
79  
80  
81  
82  
83  
84  
85 =head2 inner
86  
87 =for sig
88  
89 Signature: (a(n); b(n); [o]c())
90 Types: (sbyte byte short ushort long ulong indx ulonglong longlong
91 float double ldouble cfloat cdouble cldouble)
92  
93 =for usage
94  
95 $c = inner($a, $b);
96 inner($a, $b, $c); # all arguments given
97 $c = $a->inner($b); # method call
98 $a->inner($b, $c);
99  
100 =for ref
101  
102 Inner product over one dimension
103  
104 c = sum_i a_i * b_i
105  
106 See also L</norm>, L<PDL::Ufunc/magnover>.
107  
108 =pod
109  
110 Broadcasts over its inputs.
111  
112 =for bad
113  
114 If C<a() * b()> contains only bad data,
115 C<c()> is set bad. Otherwise C<c()> will have its bad flag cleared,
116 as it will not contain any bad values.
117  
118 =cut
119  
120  
121  
122  
123 *inner = \&PDL::inner;
124  
125  
126  
127  
128  
129  
130 =head2 outer
131  
132 =for sig
133  
134 Signature: (a(n); b(m); [o]c(n,m))
135 Types: (sbyte byte short ushort long ulong indx ulonglong longlong
136 float double ldouble cfloat cdouble cldouble)
137  
138 =for usage
139  
140 $c = outer($a, $b);
141 outer($a, $b, $c); # all arguments given
142 $c = $a->outer($b); # method call
143 $a->outer($b, $c);
144  
145 =for ref
146  
147 outer product over one dimension
148  
149 Naturally, it is possible to achieve the effects of outer
150 product simply by broadcasting over the "C<*>"
151 operator but this function is provided for convenience.
152  
153 =pod
154  
155 Broadcasts over its inputs.
156  
157 =for bad
158  
159 C<outer> processes bad values.
160 It will set the bad-value flag of all output ndarrays if the flag is set for any of the input ndarrays.
161  
162 =cut
163  
164  
165  
166  
167 *outer = \&PDL::outer;
168  
169  
170  
171  
172  
173 #line 98 "lib/PDL/Primitive.pd"
174  
175 =head2 x
176  
177 =for sig
178  
179 Signature: (a(i,z), b(x,i),[o]c(x,z))
180  
181 =for ref
182  
183 Matrix multiplication
184  
185 PDL overloads the C<x> operator (normally the repeat operator) for
186 matrix multiplication. The number of columns (size of the 0
187 dimension) in the left-hand argument must normally equal the number of
188 rows (size of the 1 dimension) in the right-hand argument.
189  
190 Row vectors are represented as (N x 1) two-dimensional PDLs, or you
191 may be sloppy and use a one-dimensional PDL. Column vectors are
192 represented as (1 x N) two-dimensional PDLs.
193  
194 Broadcasting occurs in the usual way, but as both the 0 and 1 dimension
195 (if present) are included in the operation, you must be sure that
196 you don't try to broadcast over either of those dims.
197  
198 Of note, due to how Perl v5.14.0 and above implement operator overloading of
199 the C<x> operator, the use of parentheses for the left operand creates a list
200 context, that is
201  
202 pdl> ( $x * $y ) x $z
203 ERROR: Argument "..." isn't numeric in repeat (x) ...
204  
205 treats C<$z> as a numeric count for the list repeat operation and does not call
206 the scalar form of the overloaded operator. To use the operator in this case,
207 use a scalar context:
208  
209 pdl> scalar( $x * $y ) x $z
210  
211 or by calling L</matmult> directly:
212  
213 pdl> ( $x * $y )->matmult( $z )
214  
215 EXAMPLES
216  
217 Here are some simple ways to define vectors and matrices:
218  
219 pdl> $r = pdl(1,2); # A row vector
220 pdl> $c = pdl([[3],[4]]); # A column vector
221 pdl> $c = pdl(3,4)->(*1); # A column vector, using NiceSlice
222 pdl> $m = pdl([[1,2],[3,4]]); # A 2x2 matrix
223  
224 Now that we have a few objects prepared, here is how to
225 matrix-multiply them:
226  
227 pdl> print $r x $m # row x matrix = row
228 [
229 [ 7 10]
230 ]
231  
232 pdl> print $m x $r # matrix x row = ERROR
233 PDL: Dim mismatch in matmult of [2x2] x [2x1]: 2 != 1
234  
235 pdl> print $m x $c # matrix x column = column
236 [
237 [ 5]
238 [11]
239 ]
240  
241 pdl> print $m x 2 # Trivial case: scalar mult.
242 [
243 [2 4]
244 [6 8]
245 ]
246  
247 pdl> print $r x $c # row x column = scalar
248 [
249 [11]
250 ]
251  
252 pdl> print $c x $r # column x row = matrix
253 [
254 [3 6]
255 [4 8]
256 ]
257  
258 INTERNALS
259  
260 The mechanics of the multiplication are carried out by the
261 L</matmult> method.
262  
263 =cut
264 #line 265 "lib/PDL/Primitive.pm"
265  
266  
267 =head2 matmult
268  
269 =for sig
270  
271 Signature: (a(t,h); b(w,t); [o]c(w,h))
272 Types: (sbyte byte short ushort long ulong indx ulonglong longlong
273 float double ldouble cfloat cdouble cldouble)
274  
275 =for usage
276  
277 $c = x $a, $b; # overloads the Perl 'x' operator
278 $c = matmult($a, $b);
279 matmult($a, $b, $c); # all arguments given
280 $c = $a->matmult($b); # method call
281 $a->matmult($b, $c);
282  
283 =for ref
284  
285 Matrix multiplication
286  
287 Notionally, matrix multiplication $x x $y is equivalent to the
288 broadcasting expression
289  
290 $x->dummy(1)->inner($y->xchg(0,1)->dummy(2),$c);
291  
292 but for large matrices that breaks CPU cache and is slow. Instead,
293 matmult calculates its result in 32x32x32 tiles, to keep the memory
294 footprint within cache as long as possible on most modern CPUs.
295  
296 For usage, see L</x>, a description of the overloaded 'x' operator
297  
298 =pod
299  
300 Broadcasts over its inputs.
301  
302 =for bad
303  
304 C<matmult> processes bad values.
305 It will set the bad-value flag of all output ndarrays if the flag is set for any of the input ndarrays.
306  
307 =cut
308  
309  
310  
311  
312  
313 #line 197 "lib/PDL/Primitive.pd"
314 sub PDL::matmult {
315 my ($x,$y,$c) = @_;
316 $y = PDL->topdl($y);
317 $c = PDL->null if !UNIVERSAL::isa($c, 'PDL');
318 while($x->getndims < 2) {$x = $x->dummy(-1)}
319 while($y->getndims < 2) {$y = $y->dummy(-1)}
320 return ($c .= $x * $y) if( ($x->dim(0)==1 && $x->dim(1)==1) ||
321 ($y->dim(0)==1 && $y->dim(1)==1) );
322 barf sprintf 'Dim mismatch in matmult of [%1$dx%2$d] x [%3$dx%4$d]: %1$d != %4$d',$x->dim(0),$x->dim(1),$y->dim(0),$y->dim(1)
323 if $y->dim(1) != $x->dim(0);
324 PDL::_matmult_int($x,$y,$c);
325 $c;
326 }
327 #line 328 "lib/PDL/Primitive.pm"
328  
329 *matmult = \&PDL::matmult;
330  
331  
332  
333  
334  
335  
336 =head2 innerwt
337  
338 =for sig
339  
340 Signature: (a(n); b(n); c(n); [o]d())
341 Types: (sbyte byte short ushort long ulong indx ulonglong longlong
342 float double ldouble cfloat cdouble cldouble)
343  
344 =for usage
345  
346 $d = innerwt($a, $b, $c);
347 innerwt($a, $b, $c, $d); # all arguments given
348 $d = $a->innerwt($b, $c); # method call
349 $a->innerwt($b, $c, $d);
350  
351 =for ref
352  
353 Weighted (i.e. triple) inner product
354  
355 d = sum_i a(i) b(i) c(i)
356  
357 =pod
358  
359 Broadcasts over its inputs.
360  
361 =for bad
362  
363 C<innerwt> processes bad values.
364 It will set the bad-value flag of all output ndarrays if the flag is set for any of the input ndarrays.
365  
366 =cut
367  
368  
369  
370  
371 *innerwt = \&PDL::innerwt;
372  
373  
374  
375  
376  
377  
378 =head2 inner2
379  
380 =for sig
381  
382 Signature: (a(n); b(n,m); c(m); [o]d())
383 Types: (sbyte byte short ushort long ulong indx ulonglong longlong
384 float double ldouble cfloat cdouble cldouble)
385  
386 =for usage
387  
388 $d = inner2($a, $b, $c);
389 inner2($a, $b, $c, $d); # all arguments given
390 $d = $a->inner2($b, $c); # method call
391 $a->inner2($b, $c, $d);
392  
393 =for ref
394  
395 Inner product of two vectors and a matrix
396  
397 d = sum_ij a(i) b(i,j) c(j)
398  
399 Note that you should probably not broadcast over C<a> and C<c> since that would be
400 very wasteful. Instead, you should use a temporary for C<b*c>.
401  
402 =pod
403  
404 Broadcasts over its inputs.
405  
406 =for bad
407  
408 C<inner2> processes bad values.
409 It will set the bad-value flag of all output ndarrays if the flag is set for any of the input ndarrays.
410  
411 =cut
412  
413  
414  
415  
416 *inner2 = \&PDL::inner2;
417  
418  
419  
420  
421  
422  
423 =head2 inner2d
424  
425 =for sig
426  
427 Signature: (a(n,m); b(n,m); [o]c())
428 Types: (sbyte byte short ushort long ulong indx ulonglong longlong
429 float double ldouble cfloat cdouble cldouble)
430  
431 =for usage
432  
433 $c = inner2d($a, $b);
434 inner2d($a, $b, $c); # all arguments given
435 $c = $a->inner2d($b); # method call
436 $a->inner2d($b, $c);
437  
438 =for ref
439  
440 Inner product over 2 dimensions.
441  
442 Equivalent to
443  
444 $c = inner($x->clump(2), $y->clump(2))
445  
446 =pod
447  
448 Broadcasts over its inputs.
449  
450 =for bad
451  
452 C<inner2d> processes bad values.
453 It will set the bad-value flag of all output ndarrays if the flag is set for any of the input ndarrays.
454  
455 =cut
456  
457  
458  
459  
460 *inner2d = \&PDL::inner2d;
461  
462  
463  
464  
465  
466  
467 =head2 inner2t
468  
469 =for sig
470  
471 Signature: (a(j,n); b(n,m); c(m,k); [t]tmp(n,k); [o]d(j,k))
472 Types: (sbyte byte short ushort long ulong indx ulonglong longlong
473 float double ldouble cfloat cdouble cldouble)
474  
475 =for usage
476  
477 $d = inner2t($a, $b, $c);
478 inner2t($a, $b, $c, $d); # all arguments given
479 $d = $a->inner2t($b, $c); # method call
480 $a->inner2t($b, $c, $d);
481  
482 =for ref
483  
484 Efficient Triple matrix product C<a*b*c>
485  
486 Efficiency comes from by using the temporary C<tmp>. This operation only
487 scales as C<N**3> whereas broadcasting using L</inner2> would scale
488 as C<N**4>.
489  
490 The reason for having this routine is that you do not need to
491 have the same broadcast-dimensions for C<tmp> as for the other arguments,
492 which in case of large numbers of matrices makes this much more
493 memory-efficient.
494  
495 It is hoped that things like this could be taken care of as a kind of
496 closure at some point.
497  
498 =pod
499  
500 Broadcasts over its inputs.
501  
502 =for bad
503  
504 C<inner2t> processes bad values.
505 It will set the bad-value flag of all output ndarrays if the flag is set for any of the input ndarrays.
506  
507 =cut
508  
509  
510  
511  
512 *inner2t = \&PDL::inner2t;
513  
514  
515  
516  
517  
518  
519 =head2 crossp
520  
521 =for sig
522  
523 Signature: (a(tri=3); b(tri); [o] c(tri))
524 Types: (sbyte byte short ushort long ulong indx ulonglong longlong
525 float double ldouble cfloat cdouble cldouble)
526  
527 =for usage
528  
529 $c = crossp($a, $b);
530 crossp($a, $b, $c); # all arguments given
531 $c = $a->crossp($b); # method call
532 $a->crossp($b, $c);
533  
534 =for ref
535  
536 Cross product of two 3D vectors
537  
538 After
539  
540 =for example
541  
542 $c = crossp $x, $y
543  
544 the inner product C<$c*$x> and C<$c*$y> will be zero, i.e. C<$c> is
545 orthogonal to C<$x> and C<$y>
546  
547 =pod
548  
549 Broadcasts over its inputs.
550  
551 =for bad
552  
553 C<crossp> does not process bad values.
554 It will set the bad-value flag of all output ndarrays if the flag is set for any of the input ndarrays.
555  
556 =cut
557  
558  
559  
560  
561 *crossp = \&PDL::crossp;
562  
563  
564  
565  
566  
567  
568 =head2 norm
569  
570 =for sig
571  
572 Signature: (vec(n); [o] norm(n))
573 Types: (sbyte byte short ushort long ulong indx ulonglong longlong
574 float double ldouble cfloat cdouble cldouble)
575  
576 =for usage
577  
578 $norm = norm($vec);
579 norm($vec, $norm); # all arguments given
580 $norm = $vec->norm; # method call
581 $vec->norm($norm);
582 $vec->inplace->norm; # can be used inplace
583 norm($vec->inplace);
584  
585 Normalises a vector to unit Euclidean length
586  
587 See also L</inner>, L<PDL::Ufunc/magnover>.
588  
589 =pod
590  
591 Can operate inplace with C<vec> as output C<norm>.
592 Broadcasts over its inputs.
593  
594 =for bad
595  
596 C<norm> processes bad values.
597 It will set the bad-value flag of all output ndarrays if the flag is set for any of the input ndarrays.
598  
599 =cut
600  
601  
602  
603  
604 *norm = \&PDL::norm;
605  
606  
607  
608  
609  
610  
611 =head2 indadd
612  
613 =for sig
614  
615 Signature: (input(n); indx ind(n); [io] sum(m))
616 Types: (sbyte byte short ushort long ulong indx ulonglong longlong
617 float double ldouble cfloat cdouble cldouble)
618  
619 =for usage
620  
621 indadd($input, $ind, $sum); # all arguments given
622 $input->indadd($ind, $sum); # method call
623  
624 =for ref
625  
626 Broadcasting index add: add C<input> to the C<ind> element of C<sum>, i.e:
627  
628 sum(ind) += input
629  
630 =for example
631  
632 Simple example:
633  
634 $x = 2;
635 $ind = 3;
636 $sum = zeroes(10);
637 indadd($x,$ind, $sum);
638 print $sum
639 #Result: ( 2 added to element 3 of $sum)
640 # [0 0 0 2 0 0 0 0 0 0]
641  
642 Broadcasting example:
643  
644 $x = pdl( 1,2,3);
645 $ind = pdl( 1,4,6);
646 $sum = zeroes(10);
647 indadd($x,$ind, $sum);
648 print $sum."\n";
649 #Result: ( 1, 2, and 3 added to elements 1,4,6 $sum)
650 # [0 1 0 0 2 0 3 0 0 0]
651  
652 =pod
653  
654 Broadcasts over its inputs.
655  
656 =for bad
657  
658 The routine barfs on bad indices, and bad inputs set target outputs bad.
659  
660 =cut
661  
662  
663  
664  
665 *indadd = \&PDL::indadd;
666  
667  
668  
669  
670  
671  
672 =head2 conv1d
673  
674 =for sig
675  
676 Signature: (a(m); kern(p); [o]b(m); int reflect)
677 Types: (sbyte byte short ushort long ulong indx ulonglong longlong
678 float double ldouble cfloat cdouble cldouble)
679  
680 =for usage
681  
682 $b = conv1d($a, $kern, $reflect);
683 conv1d($a, $kern, $b, $reflect); # all arguments given
684 $b = $a->conv1d($kern, $reflect); # method call
685 $a->conv1d($kern, $b, $reflect);
686  
687 =for ref
688  
689 1D convolution along first dimension
690  
691 The m-th element of the discrete convolution of an input ndarray
692 C<$a> of size C<$M>, and a kernel ndarray C<$kern> of size C<$P>, is
693 calculated as
694  
695 n = ($P-1)/2
696 ====
697 \
698 ($a conv1d $kern)[m] = > $a_ext[m - n] * $kern[n]
699 /
700 ====
701 n = -($P-1)/2
702  
703 where C<$a_ext> is either the periodic (or reflected) extension of
704 C<$a> so it is equal to C<$a> on C< 0..$M-1 > and equal to the
705 corresponding periodic/reflected image of C<$a> outside that range.
706  
707 =for example
708  
709 $con = conv1d sequence(10), pdl(-1,0,1);
710  
711 $con = conv1d sequence(10), pdl(-1,0,1), {Boundary => 'reflect'};
712  
713 By default, periodic boundary conditions are assumed (i.e. wrap around).
714 Alternatively, you can request reflective boundary conditions using
715 the C<Boundary> option:
716  
717 {Boundary => 'reflect'} # case in 'reflect' doesn't matter
718  
719 The convolution is performed along the first dimension. To apply it across
720 another dimension use the slicing routines, e.g.
721  
722 $y = $x->mv(2,0)->conv1d($kernel)->mv(0,2); # along third dim
723  
724 This function is useful for broadcasted filtering of 1D signals.
725  
726 Compare also L<conv2d|PDL::Image2D/conv2d>, L<convolve|PDL::ImageND/convolve>,
727 L<fftconvolve|PDL::FFT/fftconvolve()>
728  
729 =for bad
730  
731 WARNING: C<conv1d> processes bad values in its inputs as
732 the numeric value of C<< $pdl->badvalue >> so it is not
733 recommended for processing pdls with bad values in them
734 unless special care is taken.
735  
736 =pod
737  
738 Broadcasts over its inputs.
739  
740 =for bad
741  
742 C<conv1d> ignores the bad-value flag of the input ndarrays.
743 It will set the bad-value flag of all output ndarrays if the flag is set for any of the input ndarrays.
744  
745 =cut
746  
747  
748  
749  
750  
751 #line 569 "lib/PDL/Primitive.pd"
752 sub PDL::conv1d {
753 my $opt = pop @_ if ref($_[-1]) eq 'HASH';
754 die 'Usage: conv1d( a(m), kern(p), [o]b(m), {Options} )'
755 if @_<2 || @_>3;
756 my($x,$kern) = @_;
757 my $c = @_ == 3 ? $_[2] : PDL->null;
758 PDL::_conv1d_int($x,$kern,$c,
759 !(defined $opt && exists $$opt{Boundary}) ? 0 :
760 lc $$opt{Boundary} eq "reflect");
761 return $c;
762 }
763 #line 764 "lib/PDL/Primitive.pm"
764  
765 *conv1d = \&PDL::conv1d;
766  
767  
768  
769  
770  
771  
772 =head2 in
773  
774 =for sig
775  
776 Signature: (a(); b(n); [o] c())
777 Types: (sbyte byte short ushort long ulong indx ulonglong longlong
778 float double ldouble cfloat cdouble cldouble)
779  
780 =for usage
781  
782 $c = in($a, $b);
783 in($a, $b, $c); # all arguments given
784 $c = $a->in($b); # method call
785 $a->in($b, $c);
786  
787 =for ref
788  
789 test if a is in the set of values b
790  
791 =for example
792  
793 $goodmsk = $labels->in($goodlabels);
794 print pdl(3,1,4,6,2)->in(pdl(2,3,3));
795 [1 0 0 0 1]
796  
797 C<in> is akin to the I<is an element of> of set theory. In principle,
798 PDL broadcasting could be used to achieve its functionality by using a
799 construct like
800  
801 $msk = ($labels->dummy(0) == $goodlabels)->orover;
802  
803 However, C<in> doesn't create a (potentially large) intermediate
804 and is generally faster.
805  
806 =pod
807  
808 Broadcasts over its inputs.
809  
810 =for bad
811  
812 C<in> does not process bad values.
813 It will set the bad-value flag of all output ndarrays if the flag is set for any of the input ndarrays.
814  
815 =cut
816  
817  
818  
819  
820 *in = \&PDL::in;
821  
822  
823  
824  
825  
826 #line 637 "lib/PDL/Primitive.pd"
827  
828 =head2 uniq
829  
830 =for ref
831  
832 return all unique elements of an ndarray
833  
834 The unique elements are returned in ascending order.
835  
836 =for example
837  
838 PDL> p pdl(2,2,2,4,0,-1,6,6)->uniq
839 [-1 0 2 4 6] # 0 is returned 2nd (sorted order)
840  
841 PDL> p pdl(2,2,2,4,nan,-1,6,6)->uniq
842 [-1 2 4 6 nan] # NaN value is returned at end
843  
844 Note: The returned pdl is 1D; any structure of the input
845 ndarray is lost. C<NaN> values are never compare equal to
846 any other values, even themselves. As a result, they are
847 always unique. C<uniq> returns the NaN values at the end
848 of the result ndarray. This follows the Matlab usage.
849  
850 See L</uniqind> if you need the indices of the unique
851 elements rather than the values.
852  
853 =for bad
854  
855 Bad values are not considered unique by uniq and are ignored.
856  
857 $x=sequence(10);
858 $x=$x->setbadif($x%3);
859 print $x->uniq;
860 [0 3 6 9]
861  
862 =cut
863  
864 *uniq = \&PDL::uniq;
865 # return unique elements of array
866 # find as jumps in the sorted array
867 # flattens in the process
868 sub PDL::uniq {
869 my ($arr) = @_;
870 return $arr if($arr->nelem == 0); # The null list is unique (CED)
871 return $arr->flat if($arr->nelem == 1); # singleton list is unique
872 my $aflat = $arr->flat;
873 my $srt = $aflat->where($aflat==$aflat)->qsort; # no NaNs or BADs for qsort
874 my $nans = $aflat->where($aflat!=$aflat);
875 my $uniq = ($srt->nelem > 1) ? $srt->where($srt != $srt->rotate(-1)) : $srt;
876 # make sure we return something if there is only one value
877 (
878 $uniq->nelem > 0 ? $uniq :
879 $srt->nelem == 0 ? $srt :
880 PDL::pdl( ref($srt), [$srt->index(0)] )
881 )->append($nans);
882 }
883  
884 #line 696 "lib/PDL/Primitive.pd"
885  
886 =head2 uniqind
887  
888 =for ref
889  
890 Return the indices of all unique elements of an ndarray
891 The order is in the order of the values to be consistent
892 with uniq. C<NaN> values never compare equal with any
893 other value and so are always unique. This follows the
894 Matlab usage.
895  
896 =for example
897  
898 PDL> p pdl(2,2,2,4,0,-1,6,6)->uniqind
899 [5 4 1 3 6] # the 0 at index 4 is returned 2nd, but...
900  
901 PDL> p pdl(2,2,2,4,nan,-1,6,6)->uniqind
902 [5 1 3 6 4] # ...the NaN at index 4 is returned at end
903  
904 Note: The returned pdl is 1D; any structure of the input
905 ndarray is lost.
906  
907 See L</uniq> if you want the unique values instead of the
908 indices.
909  
910 =for bad
911  
912 Bad values are not considered unique by uniqind and are ignored.
913  
914 =cut
915  
916 *uniqind = \&PDL::uniqind;
917 # return unique elements of array
918 # find as jumps in the sorted array
919 # flattens in the process
920 sub PDL::uniqind {
921 use PDL::Core 'barf';
922 my ($arr) = @_;
923 return $arr if($arr->nelem == 0); # The null list is unique (CED)
924 # Different from uniq we sort and store the result in an intermediary
925 my $aflat = $arr->flat;
926 my $nanind = which($aflat!=$aflat); # NaN indexes
927 my $good = PDL->sequence(indx, $aflat->dims)->where($aflat==$aflat); # good indexes
928 my $i_srt = $aflat->where($aflat==$aflat)->qsorti; # no BAD or NaN values for qsorti
929 my $srt = $aflat->where($aflat==$aflat)->index($i_srt);
930 my $uniqind;
931 if ($srt->nelem > 0) {
932 $uniqind = which($srt != $srt->rotate(-1));
933 $uniqind = $i_srt->slice('0') if $uniqind->isempty;
934 } else {
935 $uniqind = which($srt);
936 }
937 # Now map back to the original space
938 my $ansind = $nanind;
939 if ( $uniqind->nelem > 0 ) {
940 $ansind = ($good->index($i_srt->index($uniqind)))->append($ansind);
941 } else {
942 $ansind = $uniqind->append($ansind);
943 }
944 return $ansind;
945 }
946  
947 #line 762 "lib/PDL/Primitive.pd"
948  
949 =head2 uniqvec
950  
951 =for ref
952  
953 Return all unique vectors out of a collection
954  
955 NOTE: If any vectors in the input ndarray have NaN values
956 they are returned at the end of the non-NaN ones. This is
957 because, by definition, NaN values never compare equal with
958 any other value.
959  
960 NOTE: The current implementation does not sort the vectors
961 containing NaN values.
962  
963 The unique vectors are returned in lexicographically sorted
964 ascending order. The 0th dimension of the input PDL is treated
965 as a dimensional index within each vector, and the 1st and any
966 higher dimensions are taken to run across vectors. The return
967 value is always 2D; any structure of the input PDL (beyond using
968 the 0th dimension for vector index) is lost.
969  
970 See also L</uniq> for a unique list of scalars; and
971 L<qsortvec|PDL::Ufunc/qsortvec> for sorting a list of vectors
972 lexicographcally.
973  
974 =for bad
975  
976 If a vector contains all bad values, it is ignored as in L</uniq>.
977 If some of the values are good, it is treated as a normal vector. For
978 example, [1 2 BAD] and [BAD 2 3] could be returned, but [BAD BAD BAD]
979 could not. Vectors containing BAD values will be returned after any
980 non-NaN and non-BAD containing vectors, followed by the NaN vectors.
981  
982 =cut
983  
984 sub PDL::uniqvec {
985 my($pdl) = shift;
986  
987 return $pdl if ( $pdl->nelem == 0 || $pdl->ndims < 2 );
988 return $pdl if ( $pdl->slice("(0)")->nelem < 2 ); # slice isn't cheap but uniqvec isn't either
989  
990 my $pdl2d = $pdl->clump(1..$pdl->ndims-1);
991 my $ngood = $pdl2d->ngoodover;
992 $pdl2d = $pdl2d->mv(0,-1)->dice($ngood->which)->mv(-1,0); # remove all-BAD vectors
993  
994 my $numnan = ($pdl2d!=$pdl2d)->sumover; # works since no all-BADs to confuse
995  
996 my $presrt = $pdl2d->mv(0,-1)->dice($numnan->not->which)->mv(0,-1); # remove vectors with any NaN values
997 my $nanvec = $pdl2d->mv(0,-1)->dice($numnan->which)->mv(0,-1); # the vectors with any NaN values
998  
999 my $srt = $presrt->qsortvec->mv(0,-1); # BADs are sorted by qsortvec
1000 my $srtdice = $srt;
1001 my $somebad = null;
1002 if ($srt->badflag) {
1003 $srtdice = $srt->dice($srt->mv(0,-1)->nbadover->not->which);
1004 $somebad = $srt->dice($srt->mv(0,-1)->nbadover->which);
1005 }
1006  
1007 my $uniq = $srtdice->nelem > 0
1008 ? ($srtdice != $srtdice->rotate(-1))->mv(0,-1)->orover->which
1009 : $srtdice->orover->which;
1010  
1011 my $ans = $uniq->nelem > 0 ? $srtdice->dice($uniq) :
1012 ($srtdice->nelem > 0) ? $srtdice->slice("0,:") :
1013 $srtdice;
1014 return $ans->append($somebad)->append($nanvec->mv(0,-1))->mv(0,-1);
1015 }
1016 #line 1017 "lib/PDL/Primitive.pm"
1017  
1018  
1019 =head2 hclip
1020  
1021 =for sig
1022  
1023 Signature: (a(); b(); [o] c())
1024 Types: (sbyte byte short ushort long ulong indx ulonglong longlong
1025 float double ldouble)
1026  
1027 =for usage
1028  
1029 $c = hclip($a, $b);
1030 hclip($a, $b, $c); # all arguments given
1031 $c = $a->hclip($b); # method call
1032 $a->hclip($b, $c);
1033 $a->inplace->hclip($b); # can be used inplace
1034 hclip($a->inplace, $b);
1035  
1036 =for ref
1037  
1038 clip (threshold) C<$a> by C<$b> (C<$b> is upper bound)
1039  
1040 =pod
1041  
1042 Can operate inplace with C<a> as output C<c>.
1043 Broadcasts over its inputs.
1044  
1045 =for bad
1046  
1047 C<hclip> processes bad values.
1048 It will set the bad-value flag of all output ndarrays if the flag is set for any of the input ndarrays.
1049  
1050 =cut
1051  
1052  
1053  
1054  
1055 *hclip = \&PDL::hclip;
1056  
1057  
1058  
1059  
1060  
1061  
1062 =head2 lclip
1063  
1064 =for sig
1065  
1066 Signature: (a(); b(); [o] c())
1067 Types: (sbyte byte short ushort long ulong indx ulonglong longlong
1068 float double ldouble)
1069  
1070 =for usage
1071  
1072 $c = lclip($a, $b);
1073 lclip($a, $b, $c); # all arguments given
1074 $c = $a->lclip($b); # method call
1075 $a->lclip($b, $c);
1076 $a->inplace->lclip($b); # can be used inplace
1077 lclip($a->inplace, $b);
1078  
1079 =for ref
1080  
1081 clip (threshold) C<$a> by C<$b> (C<$b> is lower bound)
1082  
1083 =pod
1084  
1085 Can operate inplace with C<a> as output C<c>.
1086 Broadcasts over its inputs.
1087  
1088 =for bad
1089  
1090 C<lclip> processes bad values.
1091 It will set the bad-value flag of all output ndarrays if the flag is set for any of the input ndarrays.
1092  
1093 =cut
1094  
1095  
1096  
1097  
1098 *lclip = \&PDL::lclip;
1099  
1100  
1101  
1102  
1103  
1104  
1105 =head2 clip
1106  
1107 =for sig
1108  
1109 Signature: (a(); l(); h(); [o] c())
1110 Types: (sbyte byte short ushort long ulong indx ulonglong longlong
1111 float double ldouble)
1112  
1113 =for ref
1114  
1115 Clip (threshold) an ndarray by (optional) upper or lower bounds.
1116  
1117 =for usage
1118  
1119 $y = $x->clip(0,3);
1120 $c = $x->clip(undef, $x);
1121  
1122 =pod
1123  
1124 Broadcasts over its inputs.
1125  
1126 =for bad
1127  
1128 C<clip> processes bad values.
1129 It will set the bad-value flag of all output ndarrays if the flag is set for any of the input ndarrays.
1130  
1131 =cut
1132  
1133  
1134  
1135  
1136  
1137 #line 873 "lib/PDL/Primitive.pd"
1138 *clip = \&PDL::clip;
1139 sub PDL::clip {
1140 my($x, $l, $h) = @_;
1141 return $x->new_or_inplace if !defined($l) && !defined($h);
1142 return $x->lclip($l) if !defined($h);
1143 return $x->hclip($h) if !defined($l);
1144 my $d;
1145 if ($x->is_inplace) {
1146 $x->set_inplace(0); $d = $x
1147 } elsif (@_ > 3) {
1148 $d=$_[3]
1149 } else {
1150 $d = PDL->nullcreate($x);
1151 }
1152 PDL::_clip_int($x,$l,$h,$d);
1153 $d;
1154 }
1155 #line 1156 "lib/PDL/Primitive.pm"
1156  
1157 *clip = \&PDL::clip;
1158  
1159  
1160  
1161  
1162  
1163  
1164 =head2 wtstat
1165  
1166 =for sig
1167  
1168 Signature: (a(n); wt(n); avg(); [o]b(); int deg)
1169 Types: (sbyte byte short ushort long ulong indx ulonglong longlong
1170 float double ldouble cfloat cdouble cldouble)
1171  
1172 =for usage
1173  
1174 $b = wtstat($a, $wt, $avg, $deg);
1175 wtstat($a, $wt, $avg, $b, $deg); # all arguments given
1176 $b = $a->wtstat($wt, $avg, $deg); # method call
1177 $a->wtstat($wt, $avg, $b, $deg);
1178  
1179 =for ref
1180  
1181 Weighted statistical moment of given degree
1182  
1183 This calculates a weighted statistic over the vector C<a>.
1184 The formula is
1185  
1186 b() = (sum_i wt_i * (a_i ** degree - avg)) / (sum_i wt_i)
1187  
1188 =pod
1189  
1190 Broadcasts over its inputs.
1191  
1192 =for bad
1193  
1194 Bad values are ignored in any calculation; C<$b> will only
1195 have its bad flag set if the output contains any bad data.
1196  
1197 =cut
1198  
1199  
1200  
1201  
1202 *wtstat = \&PDL::wtstat;
1203  
1204  
1205  
1206  
1207  
1208  
1209 =head2 statsover
1210  
1211 =for sig
1212  
1213 Signature: (a(n); w(n); float+ [o]avg(); float+ [o]prms(); int+ [o]min(); int+ [o]max(); float+ [o]adev(); float+ [o]rms())
1214 Types: (sbyte byte short ushort long ulong indx ulonglong longlong
1215 float double ldouble)
1216  
1217 =for ref
1218  
1219 Calculate useful statistics over a dimension of an ndarray
1220  
1221 =for usage
1222  
1223 ($mean,$prms,$median,$min,$max,$adev,$rms) = statsover($ndarray, $weights);
1224  
1225 This utility function calculates various useful
1226 quantities of an ndarray. These are:
1227  
1228 =over 3
1229  
1230 =item * the mean:
1231  
1232 MEAN = sum (x)/ N
1233  
1234 with C<N> being the number of elements in x
1235  
1236 =item * the population RMS deviation from the mean:
1237  
1238 PRMS = sqrt( sum( (x-mean(x))^2 )/(N-1) )
1239  
1240 The population deviation is the best-estimate of the deviation
1241 of the population from which a sample is drawn.
1242  
1243 =item * the median
1244  
1245 The median is the 50th percentile data value. Median is found by
1246 L<medover|PDL::Ufunc/medover>, so WEIGHTING IS IGNORED FOR THE MEDIAN CALCULATION.
1247  
1248 =item * the minimum
1249  
1250 =item * the maximum
1251  
1252 =item * the average absolute deviation:
1253  
1254 AADEV = sum( abs(x-mean(x)) )/N
1255  
1256 =item * RMS deviation from the mean:
1257  
1258 RMS = sqrt(sum( (x-mean(x))^2 )/N)
1259  
1260 (also known as the root-mean-square deviation, or the square root of the
1261 variance)
1262  
1263 =back
1264  
1265 This operator is a projection operator so the calculation
1266 will take place over the final dimension. Thus if the input
1267 is N-dimensional each returned value will be N-1 dimensional,
1268 to calculate the statistics for the entire ndarray either
1269 use C<clump(-1)> directly on the ndarray or call C<stats>.
1270  
1271 =pod
1272  
1273 Broadcasts over its inputs.
1274  
1275 =for bad
1276  
1277 Bad values are simply ignored in the calculation, effectively reducing
1278 the sample size. If all data are bad then the output data are marked bad.
1279  
1280 =cut
1281  
1282  
1283  
1284  
1285  
1286 #line 983 "lib/PDL/Primitive.pd"
1287 sub PDL::statsover {
1288 barf('Usage: ($mean,[$prms, $median, $min, $max, $adev, $rms]) = statsover($data,[$weights])') if @_>2;
1289 my ($data, $weights) = @_;
1290 $weights //= $data->ones();
1291 my $median = $data->medover;
1292 my $mean = PDL->nullcreate($data);
1293 my $rms = PDL->nullcreate($data);
1294 my $min = PDL->nullcreate($data);
1295 my $max = PDL->nullcreate($data);
1296 my $adev = PDL->nullcreate($data);
1297 my $prms = PDL->nullcreate($data);
1298 PDL::_statsover_int($data, $weights, $mean, $prms, $min, $max, $adev, $rms);
1299 wantarray ? ($mean, $prms, $median, $min, $max, $adev, $rms) : $mean;
1300 }
1301 #line 1302 "lib/PDL/Primitive.pm"
1302  
1303 *statsover = \&PDL::statsover;
1304  
1305  
1306  
1307  
1308  
1309 #line 1060 "lib/PDL/Primitive.pd"
1310  
1311 =head2 stats
1312  
1313 =for ref
1314  
1315 Calculates useful statistics on an ndarray
1316  
1317 =for usage
1318  
1319 ($mean,$prms,$median,$min,$max,$adev,$rms) = stats($ndarray,[$weights]);
1320  
1321 This utility calculates all the most useful quantities in one call.
1322 It works the same way as L</statsover>, except that the quantities are
1323 calculated considering the entire input PDL as a single sample, rather
1324 than as a collection of rows. See L</statsover> for definitions of the
1325 returned quantities.
1326  
1327 =for bad
1328  
1329 Bad values are handled; if all input values are bad, then all of the output
1330 values are flagged bad.
1331  
1332 =cut
1333  
1334 *stats = \&PDL::stats;
1335 sub PDL::stats {
1336 barf('Usage: ($mean,[$rms]) = stats($data,[$weights])') if @_>2;
1337 my ($data,$weights) = @_;
1338  
1339 # Ensure that $weights is properly broadcasted over; this could be
1340 # done rather more efficiently...
1341 if(defined $weights) {
1342 $weights = pdl($weights) unless UNIVERSAL::isa($weights,'PDL');
1343 if( ($weights->ndims != $data->ndims) or
1344 (pdl($weights->dims) != pdl($data->dims))->or
1345 ) {
1346 $weights = $weights + zeroes($data)
1347 }
1348 $weights = $weights->flat;
1349 }
1350  
1351 return PDL::statsover($data->flat,$weights);
1352 }
1353 #line 1354 "lib/PDL/Primitive.pm"
1354  
1355  
1356 =head2 histogram
1357  
1358 =for sig
1359  
1360 Signature: (in(n); int+[o] hist(m); double step; double min; IV msize => m)
1361 Types: (sbyte byte short ushort long ulong indx ulonglong longlong
1362 float double ldouble cfloat cdouble cldouble)
1363  
1364 =for ref
1365  
1366 Calculates a histogram for given stepsize and minimum.
1367  
1368 =for usage
1369  
1370 $h = histogram($data, $step, $min, $numbins);
1371 $hist = zeroes $numbins; # Put histogram in existing ndarray.
1372 histogram($data, $hist, $step, $min, $numbins);
1373  
1374 The histogram will contain C<$numbins> bins starting from C<$min>, each
1375 C<$step> wide. The value in each bin is the number of
1376 values in C<$data> that lie within the bin limits.
1377  
1378 Data below the lower limit is put in the first bin, and data above the
1379 upper limit is put in the last bin.
1380  
1381 The output is reset in a different broadcastloop so that you
1382 can take a histogram of C<$a(10,12)> into C<$b(15)> and get the result
1383 you want.
1384  
1385 For a higher-level interface, see L<hist|PDL::Basic/hist>.
1386  
1387 =for example
1388  
1389 pdl> p histogram(pdl(1,1,2),1,0,3)
1390 [0 2 1]
1391  
1392 =pod
1393  
1394 Broadcasts over its inputs.
1395  
1396 =for bad
1397  
1398 C<histogram> processes bad values.
1399 It will set the bad-value flag of all output ndarrays if the flag is set for any of the input ndarrays.
1400  
1401 =cut
1402  
1403  
1404  
1405  
1406 *histogram = \&PDL::histogram;
1407  
1408  
1409  
1410  
1411  
1412  
1413 =head2 whistogram
1414  
1415 =for sig
1416  
1417 Signature: (in(n); float+ wt(n);float+[o] hist(m); double step; double min; IV msize => m)
1418 Types: (sbyte byte short ushort long ulong indx ulonglong longlong
1419 float double ldouble cfloat cdouble cldouble)
1420  
1421 =for ref
1422  
1423 Calculates a histogram from weighted data for given stepsize and minimum.
1424  
1425 =for usage
1426  
1427 $h = whistogram($data, $weights, $step, $min, $numbins);
1428 $hist = zeroes $numbins; # Put histogram in existing ndarray.
1429 whistogram($data, $weights, $hist, $step, $min, $numbins);
1430  
1431 The histogram will contain C<$numbins> bins starting from C<$min>, each
1432 C<$step> wide. The value in each bin is the sum of the values in C<$weights>
1433 that correspond to values in C<$data> that lie within the bin limits.
1434  
1435 Data below the lower limit is put in the first bin, and data above the
1436 upper limit is put in the last bin.
1437  
1438 The output is reset in a different broadcastloop so that you
1439 can take a histogram of C<$a(10,12)> into C<$b(15)> and get the result
1440 you want.
1441  
1442 =for example
1443  
1444 pdl> p whistogram(pdl(1,1,2), pdl(0.1,0.1,0.5), 1, 0, 4)
1445 [0 0.2 0.5 0]
1446  
1447 =pod
1448  
1449 Broadcasts over its inputs.
1450  
1451 =for bad
1452  
1453 C<whistogram> processes bad values.
1454 It will set the bad-value flag of all output ndarrays if the flag is set for any of the input ndarrays.
1455  
1456 =cut
1457  
1458  
1459  
1460  
1461 *whistogram = \&PDL::whistogram;
1462  
1463  
1464  
1465  
1466  
1467  
1468 =head2 histogram2d
1469  
1470 =for sig
1471  
1472 Signature: (ina(n); inb(n); int+[o] hist(ma,mb); double stepa; double mina; IV masize => ma;
1473 double stepb; double minb; IV mbsize => mb;)
1474 Types: (sbyte byte short ushort long ulong indx ulonglong longlong
1475 float double ldouble cfloat cdouble cldouble)
1476  
1477 =for ref
1478  
1479 Calculates a 2d histogram.
1480  
1481 =for usage
1482  
1483 $h = histogram2d($datax, $datay, $stepx, $minx,
1484 $nbinx, $stepy, $miny, $nbiny);
1485 $hist = zeroes $nbinx, $nbiny; # Put histogram in existing ndarray.
1486 histogram2d($datax, $datay, $hist, $stepx, $minx,
1487 $nbinx, $stepy, $miny, $nbiny);
1488  
1489 The histogram will contain C<$nbinx> x C<$nbiny> bins, with the lower
1490 limits of the first one at C<($minx, $miny)>, and with bin size
1491 C<($stepx, $stepy)>.
1492 The value in each bin is the number of
1493 values in C<$datax> and C<$datay> that lie within the bin limits.
1494  
1495 Data below the lower limit is put in the first bin, and data above the
1496 upper limit is put in the last bin.
1497  
1498 =for example
1499  
1500 pdl> p histogram2d(pdl(1,1,1,2,2),pdl(2,1,1,1,1),1,0,3,1,0,3)
1501 [
1502 [0 0 0]
1503 [0 2 2]
1504 [0 1 0]
1505 ]
1506  
1507 =pod
1508  
1509 Broadcasts over its inputs.
1510  
1511 =for bad
1512  
1513 C<histogram2d> processes bad values.
1514 It will set the bad-value flag of all output ndarrays if the flag is set for any of the input ndarrays.
1515  
1516 =cut
1517  
1518  
1519  
1520  
1521 *histogram2d = \&PDL::histogram2d;
1522  
1523  
1524  
1525  
1526  
1527  
1528 =head2 whistogram2d
1529  
1530 =for sig
1531  
1532 Signature: (ina(n); inb(n); float+ wt(n);float+[o] hist(ma,mb); double stepa; double mina; IV masize => ma;
1533 double stepb; double minb; IV mbsize => mb;)
1534 Types: (sbyte byte short ushort long ulong indx ulonglong longlong
1535 float double ldouble cfloat cdouble cldouble)
1536  
1537 =for ref
1538  
1539 Calculates a 2d histogram from weighted data.
1540  
1541 =for usage
1542  
1543 $h = whistogram2d($datax, $datay, $weights,
1544 $stepx, $minx, $nbinx, $stepy, $miny, $nbiny);
1545 $hist = zeroes $nbinx, $nbiny; # Put histogram in existing ndarray.
1546 whistogram2d($datax, $datay, $weights, $hist,
1547 $stepx, $minx, $nbinx, $stepy, $miny, $nbiny);
1548  
1549 The histogram will contain C<$nbinx> x C<$nbiny> bins, with the lower
1550 limits of the first one at C<($minx, $miny)>, and with bin size
1551 C<($stepx, $stepy)>.
1552 The value in each bin is the sum of the values in
1553 C<$weights> that correspond to values in C<$datax> and C<$datay> that lie within the bin limits.
1554  
1555 Data below the lower limit is put in the first bin, and data above the
1556 upper limit is put in the last bin.
1557  
1558 =for example
1559  
1560 pdl> p whistogram2d(pdl(1,1,1,2,2),pdl(2,1,1,1,1),pdl(0.1,0.2,0.3,0.4,0.5),1,0,3,1,0,3)
1561 [
1562 [ 0 0 0]
1563 [ 0 0.5 0.9]
1564 [ 0 0.1 0]
1565 ]
1566  
1567 =pod
1568  
1569 Broadcasts over its inputs.
1570  
1571 =for bad
1572  
1573 C<whistogram2d> processes bad values.
1574 It will set the bad-value flag of all output ndarrays if the flag is set for any of the input ndarrays.
1575  
1576 =cut
1577  
1578  
1579  
1580  
1581 *whistogram2d = \&PDL::whistogram2d;
1582  
1583  
1584  
1585  
1586  
1587  
1588 =head2 fibonacci
1589  
1590 =for sig
1591  
1592 Signature: (i(n); [o]x(n))
1593 Types: (sbyte byte short ushort long ulong indx ulonglong longlong
1594 float double ldouble cfloat cdouble cldouble)
1595  
1596 =for usage
1597  
1598 $x = fibonacci($i);
1599 fibonacci($i, $x); # all arguments given
1600 $x = $i->fibonacci; # method call
1601 $i->fibonacci($x);
1602 $i->inplace->fibonacci; # can be used inplace
1603 fibonacci($i->inplace);
1604  
1605 =for ref
1606  
1607 Constructor - a vector with Fibonacci's sequence
1608  
1609 =pod
1610  
1611 Can operate inplace with C<i> as output C<x>.
1612 Broadcasts over its inputs.
1613  
1614 =for bad
1615  
1616 C<fibonacci> does not process bad values.
1617 It will set the bad-value flag of all output ndarrays if the flag is set for any of the input ndarrays.
1618  
1619 =cut
1620  
1621  
1622  
1623  
1624  
1625 #line 1328 "lib/PDL/Primitive.pd"
1626 sub fibonacci { ref($_[0]) && ref($_[0]) ne 'PDL::Type' ? $_[0]->fibonacci : PDL->fibonacci(@_) }
1627 sub PDL::fibonacci{
1628 my $x = &PDL::Core::_construct;
1629 my $is_inplace = $x->is_inplace;
1630 my ($in, $out) = $x->flat;
1631 $out = $is_inplace ? $in->inplace : PDL->null;
1632 PDL::_fibonacci_int($in, $out);
1633 $out;
1634 }
1635 #line 1636 "lib/PDL/Primitive.pm"
1636  
1637  
1638 =head2 append
1639  
1640 =for sig
1641  
1642 Signature: (a(n); b(m); [o] c(mn=CALC($SIZE(n)+$SIZE(m))))
1643 Types: (sbyte byte short ushort long ulong indx ulonglong longlong
1644 float double ldouble cfloat cdouble cldouble)
1645  
1646 =for usage
1647  
1648 $c = append($a, $b);
1649 append($a, $b, $c); # all arguments given
1650 $c = $a->append($b); # method call
1651 $a->append($b, $c);
1652  
1653 =for ref
1654  
1655 append two ndarrays by concatenating along their first dimensions
1656  
1657 =for example
1658  
1659 $x = ones(2,4,7);
1660 $y = sequence 5;
1661 $c = $x->append($y); # size of $c is now (7,4,7) (a jumbo-ndarray ;)
1662  
1663 C<append> appends two ndarrays along their first dimensions. The rest of the
1664 dimensions must be compatible in the broadcasting sense. The resulting
1665 size of the first dimension is the sum of the sizes of the first dimensions
1666 of the two argument ndarrays - i.e. C<n + m>.
1667  
1668 Similar functions include L</glue> (below), which can append more
1669 than two ndarrays along an arbitrary dimension, and
1670 L<cat|PDL::Core/cat>, which can append more than two ndarrays that all
1671 have the same sized dimensions.
1672  
1673 =pod
1674  
1675 Broadcasts over its inputs.
1676  
1677 =for bad
1678  
1679 C<append> does not process bad values.
1680 It will set the bad-value flag of all output ndarrays if the flag is set for any of the input ndarrays.
1681  
1682 =cut
1683  
1684  
1685  
1686  
1687  
1688 #line 1354 "lib/PDL/Primitive.pd"
1689  
1690 sub PDL::append {
1691 my ($i1, $i2, $o) = map PDL->topdl($_), @_;
1692 $_ = empty() for grep $_->isnull, $i1, $i2;
1693 my $nempty = grep $_->isempty, $i1, $i2;
1694 if ($nempty == 2) {
1695 my @dims = $i1->dims;
1696 $dims[0] += $i2->dim(0);
1697 return PDL->zeroes($i1->type, @dims);
1698 }
1699 $o //= PDL->null;
1700 $o .= $i1->isempty ? $i2 : $i1, return $o if $nempty == 1;
1701 PDL::_append_int($i1, $i2->convert($i1->type), $o);
1702 $o;
1703 }
1704
1705 #line 1706 "lib/PDL/Primitive.pm"
1706  
1707 *append = \&PDL::append;
1708  
1709  
1710  
1711  
1712  
1713 #line 1398 "lib/PDL/Primitive.pd"
1714  
1715 =head2 glue
1716  
1717 =for usage
1718  
1719 $c = $x->glue(<dim>,$y,...)
1720  
1721 =for ref
1722  
1723 Glue two or more PDLs together along an arbitrary dimension
1724 (N-D L</append>).
1725  
1726 Sticks $x, $y, and all following arguments together along the
1727 specified dimension. All other dimensions must be compatible in the
1728 broadcasting sense.
1729  
1730 Glue is permissive, in the sense that every PDL is treated as having an
1731 infinite number of trivial dimensions of order 1 -- so C<< $x->glue(3,$y) >>
1732 works, even if $x and $y are only one dimensional.
1733  
1734 If one of the PDLs has no elements, it is ignored. Likewise, if one
1735 of them is actually the undefined value, it is treated as if it had no
1736 elements.
1737  
1738 If the first parameter is a defined perl scalar rather than a pdl,
1739 then it is taken as a dimension along which to glue everything else,
1740 so you can say C<$cube = PDL::glue(3,@image_list);> if you like.
1741  
1742 C<glue> is implemented in pdl, using a combination of L<xchg|PDL::Slices/xchg> and
1743 L</append>. It should probably be updated (one day) to a pure PP
1744 function.
1745  
1746 Similar functions include L</append> (above), which appends
1747 only two ndarrays along their first dimension, and
1748 L<cat|PDL::Core/cat>, which can append more than two ndarrays that all
1749 have the same sized dimensions.
1750  
1751 =cut
1752  
1753 sub PDL::glue {
1754 my ($x, $dim) = splice @_, 0, 2;
1755 ($dim, $x) = ($x, $dim) if defined $x && !ref $x;
1756 confess 'dimension must be Perl scalar' if ref $dim;
1757 if (!defined $x || $x->nelem==0) {
1758 return $x unless @_;
1759 return shift if @_<=1;
1760 $x = shift;
1761 return PDL::glue($x,$dim,@_);
1762 }
1763 if ($dim - $x->dim(0) > 100) {
1764 warn "warning: PDL::glue allocating >100 dimensions!\n";
1765 }
1766 while ($dim >= $x->ndims) {
1767 $x = $x->dummy(-1,1);
1768 }
1769 $x = $x->xchg(0,$dim) if 0 != $dim;
1770 while (@_) {
1771 my $y = shift;
1772 next unless defined $y && $y->nelem;
1773 while ($dim >= $y->ndims) {
1774 $y = $y->dummy(-1,1);
1775 }
1776 $y = $y->xchg(0,$dim) if 0 != $dim;
1777 $x = $x->append($y);
1778 }
1779 0 == $dim ? $x : $x->xchg(0,$dim);
1780 }
1781 #line 1782 "lib/PDL/Primitive.pm"
1782  
1783 *axisvalues = \&PDL::axisvalues;
1784  
1785  
1786  
1787  
1788  
1789  
1790 =head2 cmpvec
1791  
1792 =for sig
1793  
1794 Signature: (a(n); b(n); sbyte [o]c())
1795 Types: (sbyte byte short ushort long ulong indx ulonglong longlong
1796 float double ldouble)
1797  
1798 =for usage
1799  
1800 $c = cmpvec($a, $b);
1801 cmpvec($a, $b, $c); # all arguments given
1802 $c = $a->cmpvec($b); # method call
1803 $a->cmpvec($b, $c);
1804  
1805 =for ref
1806  
1807 Compare two vectors lexicographically.
1808  
1809 Returns -1 if a is less, 1 if greater, 0 if equal.
1810  
1811 =pod
1812  
1813 Broadcasts over its inputs.
1814  
1815 =for bad
1816  
1817 The output is bad if any input values up to the point of inequality are
1818 bad - any after are ignored.
1819  
1820 =cut
1821  
1822  
1823  
1824  
1825 *cmpvec = \&PDL::cmpvec;
1826  
1827  
1828  
1829  
1830  
1831  
1832 =head2 eqvec
1833  
1834 =for sig
1835  
1836 Signature: (a(n); b(n); sbyte [o]c())
1837 Types: (sbyte byte short ushort long ulong indx ulonglong longlong
1838 float double ldouble)
1839  
1840 =for usage
1841  
1842 $c = eqvec($a, $b);
1843 eqvec($a, $b, $c); # all arguments given
1844 $c = $a->eqvec($b); # method call
1845 $a->eqvec($b, $c);
1846  
1847 =for ref
1848  
1849 Compare two vectors, returning 1 if equal, 0 if not equal.
1850  
1851 =pod
1852  
1853 Broadcasts over its inputs.
1854  
1855 =for bad
1856  
1857 The output is bad if any input values are bad.
1858  
1859 =cut
1860  
1861  
1862  
1863  
1864 *eqvec = \&PDL::eqvec;
1865  
1866  
1867  
1868  
1869  
1870  
1871 =head2 enumvec
1872  
1873 =for sig
1874  
1875 Signature: (v(M,N); indx [o]k(N))
1876 Types: (sbyte byte short ushort long ulong indx ulonglong longlong
1877 float double ldouble)
1878  
1879 =for usage
1880  
1881 $k = enumvec($v);
1882 enumvec($v, $k); # all arguments given
1883 $k = $v->enumvec; # method call
1884 $v->enumvec($k);
1885  
1886 =for ref
1887  
1888 Enumerate a list of vectors with locally unique keys.
1889  
1890 Given a sorted list of vectors $v, generate a vector $k containing locally unique keys for the elements of $v
1891 (where an "element" is a vector of length $M occurring in $v).
1892  
1893 Note that the keys returned in $k are only unique over a run of a single vector in $v,
1894 so that each unique vector in $v has at least one 0 (zero) index in $k associated with it.
1895 If you need global keys, see enumvecg().
1896  
1897 Contributed by Bryan Jurish E<lt>moocow@cpan.orgE<gt>.
1898  
1899 =pod
1900  
1901 Broadcasts over its inputs.
1902  
1903 =for bad
1904  
1905 C<enumvec> does not process bad values.
1906 It will set the bad-value flag of all output ndarrays if the flag is set for any of the input ndarrays.
1907  
1908 =cut
1909  
1910  
1911  
1912  
1913 *enumvec = \&PDL::enumvec;
1914  
1915  
1916  
1917  
1918  
1919  
1920 =head2 enumvecg
1921  
1922 =for sig
1923  
1924 Signature: (v(M,N); indx [o]k(N))
1925 Types: (sbyte byte short ushort long ulong indx ulonglong longlong
1926 float double ldouble)
1927  
1928 =for usage
1929  
1930 $k = enumvecg($v);
1931 enumvecg($v, $k); # all arguments given
1932 $k = $v->enumvecg; # method call
1933 $v->enumvecg($k);
1934  
1935 =for ref
1936  
1937 Enumerate a list of vectors with globally unique keys.
1938  
1939 Given a sorted list of vectors $v, generate a vector $k containing globally unique keys for the elements of $v
1940 (where an "element" is a vector of length $M occurring in $v).
1941 Basically does the same thing as:
1942  
1943 $k = $v->vsearchvec($v->uniqvec);
1944  
1945 ... but somewhat more efficiently.
1946  
1947 Contributed by Bryan Jurish E<lt>moocow@cpan.orgE<gt>.
1948  
1949 =pod
1950  
1951 Broadcasts over its inputs.
1952  
1953 =for bad
1954  
1955 C<enumvecg> does not process bad values.
1956 It will set the bad-value flag of all output ndarrays if the flag is set for any of the input ndarrays.
1957  
1958 =cut
1959  
1960  
1961  
1962  
1963 *enumvecg = \&PDL::enumvecg;
1964  
1965  
1966  
1967  
1968  
1969  
1970 =head2 vsearchvec
1971  
1972 =for sig
1973  
1974 Signature: (find(M); which(M,N); indx [o]found())
1975 Types: (sbyte byte short ushort long ulong indx ulonglong longlong
1976 float double ldouble)
1977  
1978 =for usage
1979  
1980 $found = vsearchvec($find, $which);
1981 vsearchvec($find, $which, $found); # all arguments given
1982 $found = $find->vsearchvec($which); # method call
1983 $find->vsearchvec($which, $found);
1984  
1985 =for ref
1986  
1987 Routine for searching N-dimensional values - akin to vsearch() for vectors.
1988  
1989 =for example
1990  
1991 $found = vsearchvec($find, $which);
1992 $nearest = $which->dice_axis(1,$found);
1993  
1994 Returns for each row-vector in C<$find> the index along dimension N
1995 of the least row vector of C<$which>
1996 greater or equal to it.
1997 C<$which> should be sorted in increasing order.
1998 If the value of C<$find> is larger
1999 than any member of C<$which>, the index to the last element of C<$which> is
2000 returned.
2001  
2002 See also: L</vsearch>.
2003 Contributed by Bryan Jurish E<lt>moocow@cpan.orgE<gt>.
2004  
2005 =pod
2006  
2007 Broadcasts over its inputs.
2008  
2009 =for bad
2010  
2011 C<vsearchvec> does not process bad values.
2012 It will set the bad-value flag of all output ndarrays if the flag is set for any of the input ndarrays.
2013  
2014 =cut
2015  
2016  
2017  
2018  
2019 *vsearchvec = \&PDL::vsearchvec;
2020  
2021  
2022  
2023  
2024  
2025  
2026 =head2 unionvec
2027  
2028 =for sig
2029  
2030 Signature: (a(M,NA); b(M,NB); [o]c(M,NC=CALC($SIZE(NA) + $SIZE(NB))); indx [o]nc())
2031 Types: (sbyte byte short ushort long ulong indx ulonglong longlong
2032 float double ldouble)
2033  
2034 =for usage
2035  
2036 ($c, $nc) = unionvec($a, $b);
2037 unionvec($a, $b, $c, $nc); # all arguments given
2038 ($c, $nc) = $a->unionvec($b); # method call
2039 $a->unionvec($b, $c, $nc);
2040  
2041 =for ref
2042  
2043 Union of two vector-valued PDLs.
2044  
2045 Input PDLs $a() and $b() B<MUST> be sorted in lexicographic order.
2046 On return, $nc() holds the actual number of vector-values in the union.
2047  
2048 In scalar context, slices $c() to the actual number of elements in the union
2049 and returns the sliced PDL.
2050  
2051 Contributed by Bryan Jurish E<lt>moocow@cpan.orgE<gt>.
2052  
2053 =pod
2054  
2055 Broadcasts over its inputs.
2056  
2057 =for bad
2058  
2059 C<unionvec> does not process bad values.
2060 It will set the bad-value flag of all output ndarrays if the flag is set for any of the input ndarrays.
2061  
2062 =cut
2063  
2064  
2065  
2066  
2067  
2068 #line 1667 "lib/PDL/Primitive.pd"
2069 sub PDL::unionvec {
2070 my ($a,$b,$c,$nc) = @_;
2071 $c = PDL->null if (!defined($nc));
2072 $nc = PDL->null if (!defined($nc));
2073 PDL::_unionvec_int($a,$b,$c,$nc);
2074 return ($c,$nc) if (wantarray);
2075 return $c->slice(",0:".($nc->max-1));
2076 }
2077 #line 2078 "lib/PDL/Primitive.pm"
2078  
2079 *unionvec = \&PDL::unionvec;
2080  
2081  
2082  
2083  
2084  
2085  
2086 =head2 intersectvec
2087  
2088 =for sig
2089  
2090 Signature: (a(M,NA); b(M,NB); [o]c(M,NC=CALC(PDLMIN($SIZE(NA),$SIZE(NB)))); indx [o]nc())
2091 Types: (sbyte byte short ushort long ulong indx ulonglong longlong
2092 float double ldouble)
2093  
2094 =for usage
2095  
2096 ($c, $nc) = intersectvec($a, $b);
2097 intersectvec($a, $b, $c, $nc); # all arguments given
2098 ($c, $nc) = $a->intersectvec($b); # method call
2099 $a->intersectvec($b, $c, $nc);
2100  
2101 =for ref
2102  
2103 Intersection of two vector-valued PDLs.
2104 Input PDLs $a() and $b() B<MUST> be sorted in lexicographic order.
2105 On return, $nc() holds the actual number of vector-values in the intersection.
2106  
2107 In scalar context, slices $c() to the actual number of elements in the intersection
2108 and returns the sliced PDL.
2109  
2110 Contributed by Bryan Jurish E<lt>moocow@cpan.orgE<gt>.
2111  
2112 =pod
2113  
2114 Broadcasts over its inputs.
2115  
2116 =for bad
2117  
2118 C<intersectvec> does not process bad values.
2119 It will set the bad-value flag of all output ndarrays if the flag is set for any of the input ndarrays.
2120  
2121 =cut
2122  
2123  
2124  
2125  
2126  
2127 #line 1726 "lib/PDL/Primitive.pd"
2128 sub PDL::intersectvec {
2129 my ($a,$b,$c,$nc) = @_;
2130 $c = PDL->null if (!defined($c));
2131 $nc = PDL->null if (!defined($nc));
2132 PDL::_intersectvec_int($a,$b,$c,$nc);
2133 return ($c,$nc) if (wantarray);
2134 my $nc_max = $nc->max;
2135 return ($nc_max > 0
2136 ? $c->slice(",0:".($nc_max-1))
2137 : $c->reshape($c->dim(0), 0, ($c->dims)[2..($c->ndims-1)]));
2138 }
2139 #line 2140 "lib/PDL/Primitive.pm"
2140  
2141 *intersectvec = \&PDL::intersectvec;
2142  
2143  
2144  
2145  
2146  
2147  
2148 =head2 setdiffvec
2149  
2150 =for sig
2151  
2152 Signature: (a(M,NA); b(M,NB); [o]c(M,NC=CALC($SIZE(NA))); indx [o]nc())
2153 Types: (sbyte byte short ushort long ulong indx ulonglong longlong
2154 float double ldouble)
2155  
2156 =for usage
2157  
2158 ($c, $nc) = setdiffvec($a, $b);
2159 setdiffvec($a, $b, $c, $nc); # all arguments given
2160 ($c, $nc) = $a->setdiffvec($b); # method call
2161 $a->setdiffvec($b, $c, $nc);
2162  
2163 =for ref
2164  
2165 Set-difference ($a() \ $b()) of two vector-valued PDLs.
2166  
2167 Input PDLs $a() and $b() B<MUST> be sorted in lexicographic order.
2168 On return, $nc() holds the actual number of vector-values in the computed vector set.
2169  
2170 In scalar context, slices $c() to the actual number of elements in the output vector set
2171 and returns the sliced PDL.
2172  
2173 Contributed by Bryan Jurish E<lt>moocow@cpan.orgE<gt>.
2174  
2175 =pod
2176  
2177 Broadcasts over its inputs.
2178  
2179 =for bad
2180  
2181 C<setdiffvec> does not process bad values.
2182 It will set the bad-value flag of all output ndarrays if the flag is set for any of the input ndarrays.
2183  
2184 =cut
2185  
2186  
2187  
2188  
2189  
2190 #line 1781 "lib/PDL/Primitive.pd"
2191 sub PDL::setdiffvec {
2192 my ($a,$b,$c,$nc) = @_;
2193 $c = PDL->null if (!defined($c));
2194 $nc = PDL->null if (!defined($nc));
2195 PDL::_setdiffvec_int($a,$b,$c,$nc);
2196 return ($c,$nc) if (wantarray);
2197 my $nc_max = $nc->max;
2198 return ($nc_max > 0
2199 ? $c->slice(",0:".($nc_max-1))
2200 : $c->reshape($c->dim(0), 0, ($c->dims)[2..($c->ndims-1)]));
2201 }
2202 #line 2203 "lib/PDL/Primitive.pm"
2203  
2204 *setdiffvec = \&PDL::setdiffvec;
2205  
2206  
2207  
2208  
2209  
2210  
2211 =head2 union_sorted
2212  
2213 =for sig
2214  
2215 Signature: (a(NA); b(NB); [o]c(NC=CALC($SIZE(NA) + $SIZE(NB))); indx [o]nc())
2216 Types: (sbyte byte short ushort long ulong indx ulonglong longlong
2217 float double ldouble)
2218  
2219 =for usage
2220  
2221 ($c, $nc) = union_sorted($a, $b);
2222 union_sorted($a, $b, $c, $nc); # all arguments given
2223 ($c, $nc) = $a->union_sorted($b); # method call
2224 $a->union_sorted($b, $c, $nc);
2225  
2226 =for ref
2227  
2228 Union of two flat sorted unique-valued PDLs.
2229 Input PDLs $a() and $b() B<MUST> be sorted in lexicographic order and contain no duplicates.
2230 On return, $nc() holds the actual number of values in the union.
2231  
2232 In scalar context, reshapes $c() to the actual number of elements in the union and returns it.
2233  
2234 Contributed by Bryan Jurish E<lt>moocow@cpan.orgE<gt>.
2235  
2236 =pod
2237  
2238 Broadcasts over its inputs.
2239  
2240 =for bad
2241  
2242 C<union_sorted> does not process bad values.
2243 It will set the bad-value flag of all output ndarrays if the flag is set for any of the input ndarrays.
2244  
2245 =cut
2246  
2247  
2248  
2249  
2250  
2251 #line 1847 "lib/PDL/Primitive.pd"
2252 sub PDL::union_sorted {
2253 my ($a,$b,$c,$nc) = @_;
2254 $c = PDL->null if (!defined($c));
2255 $nc = PDL->null if (!defined($nc));
2256 PDL::_union_sorted_int($a,$b,$c,$nc);
2257 return ($c,$nc) if (wantarray);
2258 return $c->slice("0:".($nc->max-1));
2259 }
2260 #line 2261 "lib/PDL/Primitive.pm"
2261  
2262 *union_sorted = \&PDL::union_sorted;
2263  
2264  
2265  
2266  
2267  
2268  
2269 =head2 intersect_sorted
2270  
2271 =for sig
2272  
2273 Signature: (a(NA); b(NB); [o]c(NC=CALC(PDLMIN($SIZE(NA),$SIZE(NB)))); indx [o]nc())
2274 Types: (sbyte byte short ushort long ulong indx ulonglong longlong
2275 float double ldouble)
2276  
2277 =for usage
2278  
2279 ($c, $nc) = intersect_sorted($a, $b);
2280 intersect_sorted($a, $b, $c, $nc); # all arguments given
2281 ($c, $nc) = $a->intersect_sorted($b); # method call
2282 $a->intersect_sorted($b, $c, $nc);
2283  
2284 =for ref
2285  
2286 Intersection of two flat sorted unique-valued PDLs.
2287 Input PDLs $a() and $b() B<MUST> be sorted in lexicographic order and contain no duplicates.
2288 On return, $nc() holds the actual number of values in the intersection.
2289  
2290 In scalar context, reshapes $c() to the actual number of elements in the intersection and returns it.
2291  
2292 Contributed by Bryan Jurish E<lt>moocow@cpan.orgE<gt>.
2293  
2294 =pod
2295  
2296 Broadcasts over its inputs.
2297  
2298 =for bad
2299  
2300 C<intersect_sorted> does not process bad values.
2301 It will set the bad-value flag of all output ndarrays if the flag is set for any of the input ndarrays.
2302  
2303 =cut
2304  
2305  
2306  
2307  
2308  
2309 #line 1906 "lib/PDL/Primitive.pd"
2310 sub PDL::intersect_sorted {
2311 my ($a,$b,$c,$nc) = @_;
2312 $c = PDL->null if (!defined($c));
2313 $nc = PDL->null if (!defined($nc));
2314 PDL::_intersect_sorted_int($a,$b,$c,$nc);
2315 return ($c,$nc) if (wantarray);
2316 my $nc_max = $nc->max;
2317 return ($nc_max > 0
2318 ? $c->slice("0:".($nc_max-1))
2319 : $c->reshape(0, ($c->dims)[1..($c->ndims-1)]));
2320 }
2321 #line 2322 "lib/PDL/Primitive.pm"
2322  
2323 *intersect_sorted = \&PDL::intersect_sorted;
2324  
2325  
2326  
2327  
2328  
2329  
2330 =head2 setdiff_sorted
2331  
2332 =for sig
2333  
2334 Signature: (a(NA); b(NB); [o]c(NC=CALC($SIZE(NA))); indx [o]nc())
2335 Types: (sbyte byte short ushort long ulong indx ulonglong longlong
2336 float double ldouble)
2337  
2338 =for usage
2339  
2340 ($c, $nc) = setdiff_sorted($a, $b);
2341 setdiff_sorted($a, $b, $c, $nc); # all arguments given
2342 ($c, $nc) = $a->setdiff_sorted($b); # method call
2343 $a->setdiff_sorted($b, $c, $nc);
2344  
2345 =for ref
2346  
2347 Set-difference ($a() \ $b()) of two flat sorted unique-valued PDLs.
2348  
2349 Input PDLs $a() and $b() B<MUST> be sorted in lexicographic order and contain no duplicate values.
2350 On return, $nc() holds the actual number of values in the computed vector set.
2351  
2352 In scalar context, reshapes $c() to the actual number of elements in the difference set and returns it.
2353  
2354 Contributed by Bryan Jurish E<lt>moocow@cpan.orgE<gt>.
2355  
2356 =pod
2357  
2358 Broadcasts over its inputs.
2359  
2360 =for bad
2361  
2362 C<setdiff_sorted> does not process bad values.
2363 It will set the bad-value flag of all output ndarrays if the flag is set for any of the input ndarrays.
2364  
2365 =cut
2366  
2367  
2368  
2369  
2370  
2371 #line 1962 "lib/PDL/Primitive.pd"
2372 sub PDL::setdiff_sorted {
2373 my ($a,$b,$c,$nc) = @_;
2374 $c = PDL->null if (!defined($c));
2375 $nc = PDL->null if (!defined($nc));
2376 PDL::_setdiff_sorted_int($a,$b,$c,$nc);
2377 return ($c,$nc) if (wantarray);
2378 my $nc_max = $nc->max;
2379 return ($nc_max > 0
2380 ? $c->slice("0:".($nc_max-1))
2381 : $c->reshape(0, ($c->dims)[1..($c->ndims-1)]));
2382 }
2383 #line 2384 "lib/PDL/Primitive.pm"
2384  
2385 *setdiff_sorted = \&PDL::setdiff_sorted;
2386  
2387  
2388  
2389  
2390  
2391  
2392 =head2 vcos
2393  
2394 =for sig
2395  
2396 Signature: (a(M,N);b(M);float+ [o]vcos(N))
2397 Types: (sbyte byte short ushort long ulong indx ulonglong longlong
2398 float double ldouble cfloat cdouble cldouble)
2399  
2400 =for usage
2401  
2402 $vcos = vcos($a, $b);
2403 vcos($a, $b, $vcos); # all arguments given
2404 $vcos = $a->vcos($b); # method call
2405 $a->vcos($b, $vcos);
2406  
2407 Computes the vector cosine similarity of a dense vector $b() with respect
2408 to each row $a(*,i) of a dense PDL $a(). This is basically the same
2409 thing as:
2410  
2411 inner($a, $b) / $a->magnover * $b->magnover
2412  
2413 ... but should be much faster to compute, and avoids allocating
2414 potentially large temporaries for the vector magnitudes. Output values
2415 in $vcos() are cosine similarities in the range [-1,1], except for
2416 zero-magnitude vectors which will result in NaN values in $vcos().
2417  
2418 You can use PDL broadcasting to batch-compute distances for multiple $b()
2419 vectors simultaneously:
2420  
2421 $bx = random($M, $NB); ##-- get $NB random vectors of size $N
2422 $vcos = vcos($a,$bx); ##-- $vcos(i,j) ~ sim($a(,i),$b(,j))
2423  
2424 Contributed by Bryan Jurish E<lt>moocow@cpan.orgE<gt>.
2425  
2426 =pod
2427  
2428 Broadcasts over its inputs.
2429  
2430 =for bad
2431  
2432 vcos() will set the bad status flag on the output $vcos() if
2433 it is set on either of the inputs $a() or $b(), but BAD values
2434 will otherwise be ignored for computing the cosine similarity.
2435  
2436 =cut
2437  
2438  
2439  
2440  
2441 *vcos = \&PDL::vcos;
2442  
2443  
2444  
2445  
2446  
2447  
2448 =head2 srandom
2449  
2450 =for sig
2451  
2452 Signature: (a())
2453 Types: (longlong)
2454  
2455 =for ref
2456  
2457 Seed random-number generator with a 64-bit int. Will generate seed data
2458 for a number of threads equal to the return-value of
2459 L<PDL::Core/online_cpus>.
2460 As of 2.062, the generator changed from Perl's generator to xoshiro256++
2461 (see L<https://prng.di.unimi.it/>).
2462 Before PDL 2.090, this was called C<srand>, but was renamed to avoid
2463 clashing with Perl's built-in.
2464  
2465 =for usage
2466  
2467 srandom(); # uses current time
2468 srandom(5); # fixed number e.g. for testing
2469  
2470 =pod
2471  
2472 Does not broadcast.
2473 Can't use POSIX threads.
2474  
2475 =for bad
2476  
2477 C<srandom> does not process bad values.
2478 It will set the bad-value flag of all output ndarrays if the flag is set for any of the input ndarrays.
2479  
2480 =cut
2481  
2482  
2483  
2484  
2485  
2486 #line 2138 "lib/PDL/Primitive.pd"
2487 *srandom = \&PDL::srandom;
2488 sub PDL::srandom { PDL::_srandom_int($_[0] // PDL::Core::seed()) }
2489 #line 2490 "lib/PDL/Primitive.pm"
2490  
2491 *srandom = \&PDL::srandom;
2492  
2493  
2494  
2495  
2496  
2497  
2498 =head2 random
2499  
2500 =for sig
2501  
2502 Signature: ([o] a())
2503 Types: (sbyte byte short ushort long ulong indx ulonglong longlong
2504 float double ldouble)
2505  
2506 =for ref
2507  
2508 Constructor which returns ndarray of random numbers, real data-types only.
2509  
2510 =for usage
2511  
2512 $x = random([type], $nx, $ny, $nz,...);
2513 $x = random $y;
2514  
2515 etc (see L<zeroes|PDL::Core/zeroes>).
2516  
2517 This is the uniform distribution between 0 and 1 (assumedly
2518 excluding 1 itself). The arguments are the same as C<zeroes>
2519 (q.v.) - i.e. one can specify dimensions, types or give
2520 a template.
2521  
2522 You can use the PDL function L</srandom> to seed the random generator.
2523 If it has not been called yet, it will be with the current time.
2524 As of 2.062, the generator changed from Perl's generator to xoshiro256++
2525 (see L<https://prng.di.unimi.it/>).
2526  
2527 =pod
2528  
2529 Broadcasts over its inputs.
2530  
2531 =for bad
2532  
2533 C<random> does not process bad values.
2534 It will set the bad-value flag of all output ndarrays if the flag is set for any of the input ndarrays.
2535  
2536 =cut
2537  
2538  
2539  
2540  
2541  
2542 #line 2178 "lib/PDL/Primitive.pd"
2543 sub random { ref($_[0]) && ref($_[0]) ne 'PDL::Type' ? $_[0]->random : PDL->random(@_) }
2544 sub PDL::random {
2545 splice @_, 1, 0, double() if !ref($_[0]) and @_<=1;
2546 my $x = &PDL::Core::_construct;
2547 PDL::_random_int($x);
2548 return $x;
2549 }
2550 #line 2551 "lib/PDL/Primitive.pm"
2551  
2552  
2553 =head2 randsym
2554  
2555 =for sig
2556  
2557 Signature: ([o] a())
2558 Types: (sbyte byte short ushort long ulong indx ulonglong longlong
2559 float double ldouble)
2560  
2561 =for ref
2562  
2563 Constructor which returns ndarray of random numbers, real data-types only.
2564  
2565 =for usage
2566  
2567 $x = randsym([type], $nx, $ny, $nz,...);
2568 $x = randsym $y;
2569  
2570 etc (see L<zeroes|PDL::Core/zeroes>).
2571  
2572 This is the uniform distribution between 0 and 1 (excluding both 0 and
2573 1, cf L</random>). The arguments are the same as C<zeroes> (q.v.) -
2574 i.e. one can specify dimensions, types or give a template.
2575  
2576 You can use the PDL function L</srandom> to seed the random generator.
2577 If it has not been called yet, it will be with the current time.
2578  
2579 =pod
2580  
2581 Broadcasts over its inputs.
2582  
2583 =for bad
2584  
2585 C<randsym> does not process bad values.
2586 It will set the bad-value flag of all output ndarrays if the flag is set for any of the input ndarrays.
2587  
2588 =cut
2589  
2590  
2591  
2592  
2593  
2594 #line 2222 "lib/PDL/Primitive.pd"
2595 sub randsym { ref($_[0]) && ref($_[0]) ne 'PDL::Type' ? $_[0]->randsym : PDL->randsym(@_) }
2596 sub PDL::randsym {
2597 splice @_, 1, 0, double() if !ref($_[0]) and @_<=1;
2598 my $x = &PDL::Core::_construct;
2599 PDL::_randsym_int($x);
2600 return $x;
2601 }
2602  
2603 #line 2233 "lib/PDL/Primitive.pd"
2604  
2605 =head2 grandom
2606  
2607 =for ref
2608  
2609 Constructor which returns ndarray of Gaussian random numbers
2610  
2611 =for usage
2612  
2613 $x = grandom([type], $nx, $ny, $nz,...);
2614 $x = grandom $y;
2615  
2616 etc (see L<zeroes|PDL::Core/zeroes>).
2617  
2618 This is generated using the math library routine C<ndtri>.
2619  
2620 Mean = 0, Stddev = 1
2621  
2622 You can use the PDL function L</srandom> to seed the random generator.
2623 If it has not been called yet, it will be with the current time.
2624  
2625 =cut
2626  
2627 sub grandom { ref($_[0]) && ref($_[0]) ne 'PDL::Type' ? $_[0]->grandom : PDL->grandom(@_) }
2628 sub PDL::grandom {
2629 my $x = &PDL::Core::_construct;
2630 use PDL::Math 'ndtri';
2631 $x .= ndtri(randsym($x));
2632 return $x;
2633 }
2634  
2635 #line 2272 "lib/PDL/Primitive.pd"
2636  
2637 =head2 vsearch
2638  
2639 =for sig
2640  
2641 Signature: ( vals(); xs(n); [o] indx(); [\%options] )
2642  
2643 =for ref
2644  
2645 Efficiently search for values in a sorted ndarray, returning indices.
2646  
2647 =for usage
2648  
2649 $idx = vsearch( $vals, $x, [\%options] );
2650 vsearch( $vals, $x, $idx, [\%options ] );
2651  
2652 B<vsearch> performs a binary search in the ordered ndarray C<$x>,
2653 for the values from C<$vals> ndarray, returning indices into C<$x>.
2654 What is a "match", and the meaning of the returned indices, are determined
2655 by the options.
2656  
2657 The C<mode> option indicates which method of searching to use, and may
2658 be one of:
2659  
2660 =over
2661  
2662 =item C<sample>
2663  
2664 invoke L<B<vsearch_sample>|/vsearch_sample>, returning indices appropriate for sampling
2665 within a distribution.
2666  
2667 =item C<insert_leftmost>
2668  
2669 invoke L<B<vsearch_insert_leftmost>|/vsearch_insert_leftmost>, returning the left-most possible
2670 insertion point which still leaves the ndarray sorted.
2671  
2672 =item C<insert_rightmost>
2673  
2674 invoke L<B<vsearch_insert_rightmost>|/vsearch_insert_rightmost>, returning the right-most possible
2675 insertion point which still leaves the ndarray sorted.
2676  
2677 =item C<match>
2678  
2679 invoke L<B<vsearch_match>|/vsearch_match>, returning the index of a matching element,
2680 else -(insertion point + 1)
2681  
2682 =item C<bin_inclusive>
2683  
2684 invoke L<B<vsearch_bin_inclusive>|/vsearch_bin_inclusive>, returning an index appropriate for binning
2685 on a grid where the left bin edges are I<inclusive> of the bin. See
2686 below for further explanation of the bin.
2687  
2688 =item C<bin_exclusive>
2689  
2690 invoke L<B<vsearch_bin_exclusive>|/vsearch_bin_exclusive>, returning an index appropriate for binning
2691 on a grid where the left bin edges are I<exclusive> of the bin. See
2692 below for further explanation of the bin.
2693  
2694 =back
2695  
2696 The default value of C<mode> is C<sample>.
2697  
2698 =for example
2699  
2700 use PDL;
2701  
2702 my @modes = qw( sample insert_leftmost insert_rightmost match
2703 bin_inclusive bin_exclusive );
2704  
2705 # Generate a sequence of 3 zeros, 3 ones, ..., 3 fours.
2706 my $x = zeroes(3,5)->yvals->flat;
2707  
2708 for my $mode ( @modes ) {
2709 # if the value is in $x
2710 my $contained = 2;
2711 my $idx_contained = vsearch( $contained, $x, { mode => $mode } );
2712 my $x_contained = $x->copy;
2713 $x_contained->slice( $idx_contained ) .= 9;
2714  
2715 # if the value is not in $x
2716 my $not_contained = 1.5;
2717 my $idx_not_contained = vsearch( $not_contained, $x, { mode => $mode } );
2718 my $x_not_contained = $x->copy;
2719 $x_not_contained->slice( $idx_not_contained ) .= 9;
2720  
2721 print sprintf("%-23s%30s\n", '$x', $x);
2722 print sprintf("%-23s%30s\n", "$mode ($contained)", $x_contained);
2723 print sprintf("%-23s%30s\n\n", "$mode ($not_contained)", $x_not_contained);
2724 }
2725  
2726 # $x [0 0 0 1 1 1 2 2 2 3 3 3 4 4 4]
2727 # sample (2) [0 0 0 1 1 1 9 2 2 3 3 3 4 4 4]
2728 # sample (1.5) [0 0 0 1 1 1 9 2 2 3 3 3 4 4 4]
2729 #
2730 # $x [0 0 0 1 1 1 2 2 2 3 3 3 4 4 4]
2731 # insert_leftmost (2) [0 0 0 1 1 1 9 2 2 3 3 3 4 4 4]
2732 # insert_leftmost (1.5) [0 0 0 1 1 1 9 2 2 3 3 3 4 4 4]
2733 #
2734 # $x [0 0 0 1 1 1 2 2 2 3 3 3 4 4 4]
2735 # insert_rightmost (2) [0 0 0 1 1 1 2 2 2 9 3 3 4 4 4]
2736 # insert_rightmost (1.5) [0 0 0 1 1 1 9 2 2 3 3 3 4 4 4]
2737 #
2738 # $x [0 0 0 1 1 1 2 2 2 3 3 3 4 4 4]
2739 # match (2) [0 0 0 1 1 1 2 9 2 3 3 3 4 4 4]
2740 # match (1.5) [0 0 0 1 1 1 2 2 9 3 3 3 4 4 4]
2741 #
2742 # $x [0 0 0 1 1 1 2 2 2 3 3 3 4 4 4]
2743 # bin_inclusive (2) [0 0 0 1 1 1 2 2 9 3 3 3 4 4 4]
2744 # bin_inclusive (1.5) [0 0 0 1 1 9 2 2 2 3 3 3 4 4 4]
2745 #
2746 # $x [0 0 0 1 1 1 2 2 2 3 3 3 4 4 4]
2747 # bin_exclusive (2) [0 0 0 1 1 9 2 2 2 3 3 3 4 4 4]
2748 # bin_exclusive (1.5) [0 0 0 1 1 9 2 2 2 3 3 3 4 4 4]
2749  
2750 Also see
2751 L<B<vsearch_sample>|/vsearch_sample>,
2752 L<B<vsearch_insert_leftmost>|/vsearch_insert_leftmost>,
2753 L<B<vsearch_insert_rightmost>|/vsearch_insert_rightmost>,
2754 L<B<vsearch_match>|/vsearch_match>,
2755 L<B<vsearch_bin_inclusive>|/vsearch_bin_inclusive>, and
2756 L<B<vsearch_bin_exclusive>|/vsearch_bin_exclusive>
2757  
2758 =cut
2759  
2760 sub vsearch {
2761 my $opt = 'HASH' eq ref $_[-1]
2762 ? pop
2763 : { mode => 'sample' };
2764  
2765 croak( "unknown options to vsearch\n" )
2766 if ( ! defined $opt->{mode} && keys %$opt )
2767 || keys %$opt > 1;
2768  
2769 my $mode = $opt->{mode};
2770 goto
2771 $mode eq 'sample' ? \&vsearch_sample
2772 : $mode eq 'insert_leftmost' ? \&vsearch_insert_leftmost
2773 : $mode eq 'insert_rightmost' ? \&vsearch_insert_rightmost
2774 : $mode eq 'match' ? \&vsearch_match
2775 : $mode eq 'bin_inclusive' ? \&vsearch_bin_inclusive
2776 : $mode eq 'bin_exclusive' ? \&vsearch_bin_exclusive
2777 : croak( "unknown vsearch mode: $mode\n" );
2778 }
2779  
2780 *PDL::vsearch = \&vsearch;
2781 #line 2782 "lib/PDL/Primitive.pm"
2782  
2783  
2784 =head2 vsearch_sample
2785  
2786 =for sig
2787  
2788 Signature: (vals(); x(n); indx [o]idx())
2789 Types: (float double ldouble)
2790  
2791 =for ref
2792  
2793 Search for values in a sorted array, return index appropriate for sampling from a distribution
2794  
2795 =for usage
2796  
2797 $idx = vsearch_sample($vals, $x);
2798  
2799 C<$x> must be sorted, but may be in decreasing or increasing
2800 order. if C<$x> is empty, then all values in C<$idx> will be
2801 set to the bad value.
2802  
2803 B<vsearch_sample> returns an index I<I> for each value I<V> of C<$vals> appropriate
2804 for sampling C<$vals>
2805  
2806
2807  
2808 I<I> has the following properties:
2809  
2810 =over
2811  
2812 =item *
2813  
2814 if C<$x> is sorted in increasing order
2815  
2816 V <= x[0] : I = 0
2817 x[0] < V <= x[-1] : I s.t. x[I-1] < V <= x[I]
2818 x[-1] < V : I = $x->nelem -1
2819  
2820 =item *
2821  
2822 if C<$x> is sorted in decreasing order
2823  
2824 V > x[0] : I = 0
2825 x[0] >= V > x[-1] : I s.t. x[I] >= V > x[I+1]
2826 x[-1] >= V : I = $x->nelem - 1
2827  
2828 =back
2829  
2830 If all elements of C<$x> are equal, I<< I = $x->nelem - 1 >>.
2831  
2832 If C<$x> contains duplicated elements, I<I> is the index of the
2833 leftmost (by position in array) duplicate if I<V> matches.
2834  
2835 =for example
2836  
2837 This function is useful e.g. when you have a list of probabilities
2838 for events and want to generate indices to events:
2839  
2840 $x = pdl(.01,.86,.93,1); # Barnsley IFS probabilities cumulatively
2841 $y = random 20;
2842 $c = vsearch_sample($y, $x); # Now, $c will have the appropriate distr.
2843  
2844 It is possible to use the L<cumusumover|PDL::Ufunc/cumusumover>
2845 function to obtain cumulative probabilities from absolute probabilities.
2846  
2847 =pod
2848  
2849 Broadcasts over its inputs.
2850  
2851 =for bad
2852  
2853 bad values in vals() result in bad values in idx()
2854  
2855 =cut
2856  
2857  
2858  
2859  
2860 *vsearch_sample = \&PDL::vsearch_sample;
2861  
2862  
2863  
2864  
2865  
2866  
2867 =head2 vsearch_insert_leftmost
2868  
2869 =for sig
2870  
2871 Signature: (vals(); x(n); indx [o]idx())
2872 Types: (float double ldouble)
2873  
2874 =for ref
2875  
2876 Determine the insertion point for values in a sorted array, inserting before duplicates.
2877  
2878 =for usage
2879  
2880 $idx = vsearch_insert_leftmost($vals, $x);
2881  
2882 C<$x> must be sorted, but may be in decreasing or increasing
2883 order. if C<$x> is empty, then all values in C<$idx> will be
2884 set to the bad value.
2885  
2886 B<vsearch_insert_leftmost> returns an index I<I> for each value I<V> of
2887 C<$vals> equal to the leftmost position (by index in array) within
2888 C<$x> that I<V> may be inserted and still maintain the order in
2889 C<$x>.
2890  
2891 Insertion at index I<I> involves shifting elements I<I> and higher of
2892 C<$x> to the right by one and setting the now empty element at index
2893 I<I> to I<V>.
2894  
2895
2896  
2897 I<I> has the following properties:
2898  
2899 =over
2900  
2901 =item *
2902  
2903 if C<$x> is sorted in increasing order
2904  
2905 V <= x[0] : I = 0
2906 x[0] < V <= x[-1] : I s.t. x[I-1] < V <= x[I]
2907 x[-1] < V : I = $x->nelem
2908  
2909 =item *
2910  
2911 if C<$x> is sorted in decreasing order
2912  
2913 V > x[0] : I = -1
2914 x[0] >= V >= x[-1] : I s.t. x[I] >= V > x[I+1]
2915 x[-1] >= V : I = $x->nelem -1
2916  
2917 =back
2918  
2919 If all elements of C<$x> are equal,
2920  
2921 i = 0
2922  
2923 If C<$x> contains duplicated elements, I<I> is the index of the
2924 leftmost (by index in array) duplicate if I<V> matches.
2925  
2926 =pod
2927  
2928 Broadcasts over its inputs.
2929  
2930 =for bad
2931  
2932 bad values in vals() result in bad values in idx()
2933  
2934 =cut
2935  
2936  
2937  
2938  
2939 *vsearch_insert_leftmost = \&PDL::vsearch_insert_leftmost;
2940  
2941  
2942  
2943  
2944  
2945  
2946 =head2 vsearch_insert_rightmost
2947  
2948 =for sig
2949  
2950 Signature: (vals(); x(n); indx [o]idx())
2951 Types: (float double ldouble)
2952  
2953 =for ref
2954  
2955 Determine the insertion point for values in a sorted array, inserting after duplicates.
2956  
2957 =for usage
2958  
2959 $idx = vsearch_insert_rightmost($vals, $x);
2960  
2961 C<$x> must be sorted, but may be in decreasing or increasing
2962 order. if C<$x> is empty, then all values in C<$idx> will be
2963 set to the bad value.
2964  
2965 B<vsearch_insert_rightmost> returns an index I<I> for each value I<V> of
2966 C<$vals> equal to the rightmost position (by index in array) within
2967 C<$x> that I<V> may be inserted and still maintain the order in
2968 C<$x>.
2969  
2970 Insertion at index I<I> involves shifting elements I<I> and higher of
2971 C<$x> to the right by one and setting the now empty element at index
2972 I<I> to I<V>.
2973  
2974
2975  
2976 I<I> has the following properties:
2977  
2978 =over
2979  
2980 =item *
2981  
2982 if C<$x> is sorted in increasing order
2983  
2984 V < x[0] : I = 0
2985 x[0] <= V < x[-1] : I s.t. x[I-1] <= V < x[I]
2986 x[-1] <= V : I = $x->nelem
2987  
2988 =item *
2989  
2990 if C<$x> is sorted in decreasing order
2991  
2992 V >= x[0] : I = -1
2993 x[0] > V >= x[-1] : I s.t. x[I] >= V > x[I+1]
2994 x[-1] > V : I = $x->nelem -1
2995  
2996 =back
2997  
2998 If all elements of C<$x> are equal,
2999  
3000 i = $x->nelem - 1
3001  
3002 If C<$x> contains duplicated elements, I<I> is the index of the
3003 leftmost (by index in array) duplicate if I<V> matches.
3004  
3005 =pod
3006  
3007 Broadcasts over its inputs.
3008  
3009 =for bad
3010  
3011 bad values in vals() result in bad values in idx()
3012  
3013 =cut
3014  
3015  
3016  
3017  
3018 *vsearch_insert_rightmost = \&PDL::vsearch_insert_rightmost;
3019  
3020  
3021  
3022  
3023  
3024  
3025 =head2 vsearch_match
3026  
3027 =for sig
3028  
3029 Signature: (vals(); x(n); indx [o]idx())
3030 Types: (float double ldouble)
3031  
3032 =for ref
3033  
3034 Match values against a sorted array.
3035  
3036 =for usage
3037  
3038 $idx = vsearch_match($vals, $x);
3039  
3040 C<$x> must be sorted, but may be in decreasing or increasing
3041 order. if C<$x> is empty, then all values in C<$idx> will be
3042 set to the bad value.
3043  
3044 B<vsearch_match> returns an index I<I> for each value I<V> of
3045 C<$vals>. If I<V> matches an element in C<$x>, I<I> is the
3046 index of that element, otherwise it is I<-( insertion_point + 1 )>,
3047 where I<insertion_point> is an index in C<$x> where I<V> may be
3048 inserted while maintaining the order in C<$x>. If C<$x> has
3049 duplicated values, I<I> may refer to any of them.
3050  
3051
3052  
3053 =pod
3054  
3055 Broadcasts over its inputs.
3056  
3057 =for bad
3058  
3059 bad values in vals() result in bad values in idx()
3060  
3061 =cut
3062  
3063  
3064  
3065  
3066 *vsearch_match = \&PDL::vsearch_match;
3067  
3068  
3069  
3070  
3071  
3072  
3073 =head2 vsearch_bin_inclusive
3074  
3075 =for sig
3076  
3077 Signature: (vals(); x(n); indx [o]idx())
3078 Types: (float double ldouble)
3079  
3080 =for ref
3081  
3082 Determine the index for values in a sorted array of bins, lower bound inclusive.
3083  
3084 =for usage
3085  
3086 $idx = vsearch_bin_inclusive($vals, $x);
3087  
3088 C<$x> must be sorted, but may be in decreasing or increasing
3089 order. if C<$x> is empty, then all values in C<$idx> will be
3090 set to the bad value.
3091  
3092 C<$x> represents the edges of contiguous bins, with the first and
3093 last elements representing the outer edges of the outer bins, and the
3094 inner elements the shared bin edges.
3095  
3096 The lower bound of a bin is inclusive to the bin, its outer bound is exclusive to it.
3097 B<vsearch_bin_inclusive> returns an index I<I> for each value I<V> of C<$vals>
3098  
3099
3100  
3101 I<I> has the following properties:
3102  
3103 =over
3104  
3105 =item *
3106  
3107 if C<$x> is sorted in increasing order
3108  
3109 V < x[0] : I = -1
3110 x[0] <= V < x[-1] : I s.t. x[I] <= V < x[I+1]
3111 x[-1] <= V : I = $x->nelem - 1
3112  
3113 =item *
3114  
3115 if C<$x> is sorted in decreasing order
3116  
3117 V >= x[0] : I = 0
3118 x[0] > V >= x[-1] : I s.t. x[I+1] > V >= x[I]
3119 x[-1] > V : I = $x->nelem
3120  
3121 =back
3122  
3123 If all elements of C<$x> are equal,
3124  
3125 i = $x->nelem - 1
3126  
3127 If C<$x> contains duplicated elements, I<I> is the index of the
3128 righmost (by index in array) duplicate if I<V> matches.
3129  
3130 =pod
3131  
3132 Broadcasts over its inputs.
3133  
3134 =for bad
3135  
3136 bad values in vals() result in bad values in idx()
3137  
3138 =cut
3139  
3140  
3141  
3142  
3143 *vsearch_bin_inclusive = \&PDL::vsearch_bin_inclusive;
3144  
3145  
3146  
3147  
3148  
3149  
3150 =head2 vsearch_bin_exclusive
3151  
3152 =for sig
3153  
3154 Signature: (vals(); x(n); indx [o]idx())
3155 Types: (float double ldouble)
3156  
3157 =for ref
3158  
3159 Determine the index for values in a sorted array of bins, lower bound exclusive.
3160  
3161 =for usage
3162  
3163 $idx = vsearch_bin_exclusive($vals, $x);
3164  
3165 C<$x> must be sorted, but may be in decreasing or increasing
3166 order. if C<$x> is empty, then all values in C<$idx> will be
3167 set to the bad value.
3168  
3169 C<$x> represents the edges of contiguous bins, with the first and
3170 last elements representing the outer edges of the outer bins, and the
3171 inner elements the shared bin edges.
3172  
3173 The lower bound of a bin is exclusive to the bin, its upper bound is inclusive to it.
3174 B<vsearch_bin_exclusive> returns an index I<I> for each value I<V> of C<$vals>.
3175  
3176
3177  
3178 I<I> has the following properties:
3179  
3180 =over
3181  
3182 =item *
3183  
3184 if C<$x> is sorted in increasing order
3185  
3186 V <= x[0] : I = -1
3187 x[0] < V <= x[-1] : I s.t. x[I] < V <= x[I+1]
3188 x[-1] < V : I = $x->nelem - 1
3189  
3190 =item *
3191  
3192 if C<$x> is sorted in decreasing order
3193  
3194 V > x[0] : I = 0
3195 x[0] >= V > x[-1] : I s.t. x[I-1] >= V > x[I]
3196 x[-1] >= V : I = $x->nelem
3197  
3198 =back
3199  
3200 If all elements of C<$x> are equal,
3201  
3202 i = $x->nelem - 1
3203  
3204 If C<$x> contains duplicated elements, I<I> is the index of the
3205 righmost (by index in array) duplicate if I<V> matches.
3206  
3207 =pod
3208  
3209 Broadcasts over its inputs.
3210  
3211 =for bad
3212  
3213 bad values in vals() result in bad values in idx()
3214  
3215 =cut
3216  
3217  
3218  
3219  
3220 *vsearch_bin_exclusive = \&PDL::vsearch_bin_exclusive;
3221  
3222  
3223  
3224  
3225  
3226  
3227 =head2 interpolate
3228  
3229 =for sig
3230  
3231 Signature: (!complex xi(); !complex x(n); y(n); [o] yi(); int [o] err())
3232 Types: (float ldouble cfloat cdouble cldouble double)
3233  
3234 =for usage
3235  
3236 ($yi, $err) = interpolate($xi, $x, $y);
3237 interpolate($xi, $x, $y, $yi, $err); # all arguments given
3238 ($yi, $err) = $xi->interpolate($x, $y); # method call
3239 $xi->interpolate($x, $y, $yi, $err);
3240  
3241 =for ref
3242  
3243 routine for 1D linear interpolation
3244  
3245 Given a set of points C<($x,$y)>, use linear interpolation
3246 to find the values C<$yi> at a set of points C<$xi>.
3247  
3248 C<interpolate> uses a binary search to find the suspects, er...,
3249 interpolation indices and therefore abscissas (ie C<$x>)
3250 have to be I<strictly> ordered (increasing or decreasing).
3251 For interpolation at lots of
3252 closely spaced abscissas an approach that uses the last index found as
3253 a start for the next search can be faster (compare Numerical Recipes
3254 C<hunt> routine). Feel free to implement that on top of the binary
3255 search if you like. For out of bounds values it just does a linear
3256 extrapolation and sets the corresponding element of C<$err> to 1,
3257 which is otherwise 0.
3258  
3259 See also L</interpol>, which uses the same routine,
3260 differing only in the handling of extrapolation - an error message
3261 is printed rather than returning an error ndarray.
3262  
3263 Note that C<interpolate> can use complex values for C<$y> and C<$yi> but
3264 C<$x> and C<$xi> must be real.
3265  
3266 =pod
3267  
3268 Broadcasts over its inputs.
3269  
3270 =for bad
3271  
3272 needs major (?) work to handles bad values
3273  
3274 =cut
3275  
3276  
3277  
3278  
3279 *interpolate = \&PDL::interpolate;
3280  
3281  
3282  
3283  
3284  
3285 #line 2946 "lib/PDL/Primitive.pd"
3286  
3287 =head2 interpol
3288  
3289 =for sig
3290  
3291 Signature: (xi(); x(n); y(n); [o] yi())
3292  
3293 =for ref
3294  
3295 routine for 1D linear interpolation
3296  
3297 =for usage
3298  
3299 $yi = interpol($xi, $x, $y)
3300  
3301 C<interpol> uses the same search method as L</interpolate>,
3302 hence C<$x> must be I<strictly> ordered (either increasing or decreasing).
3303 The difference occurs in the handling of out-of-bounds values; here
3304 an error message is printed.
3305  
3306 =cut
3307  
3308 # kept in for backwards compatibility
3309 sub interpol ($$$;$) {
3310 my $xi = shift;
3311 my $x = shift;
3312 my $y = shift;
3313 my $yi = @_ == 1 ? $_[0] : PDL->null;
3314 interpolate( $xi, $x, $y, $yi, my $err = PDL->null );
3315 print "some values had to be extrapolated\n"
3316 if any $err;
3317 return $yi if @_ == 0;
3318 } # sub: interpol()
3319 *PDL::interpol = \&interpol;
3320  
3321 #line 2984 "lib/PDL/Primitive.pd"
3322  
3323 =head2 interpND
3324  
3325 =for ref
3326  
3327 Interpolate values from an N-D ndarray, with switchable method
3328  
3329 =for example
3330  
3331 $source = 10*xvals(10,10) + yvals(10,10);
3332 $index = pdl([[2.2,3.5],[4.1,5.0]],[[6.0,7.4],[8,9]]);
3333 print $source->interpND( $index );
3334  
3335 InterpND acts like L<indexND|PDL::Slices/indexND>,
3336 collapsing C<$index> by lookup
3337 into C<$source>; but it does interpolation rather than direct sampling.
3338 The interpolation method and boundary condition are switchable via
3339 an options hash.
3340  
3341 By default, linear or sample interpolation is used, with constant
3342 value outside the boundaries of the source pdl. No dataflow occurs,
3343 because in general the output is computed rather than indexed.
3344  
3345 All the interpolation methods treat the pixels as value-centered, so
3346 the C<sample> method will return C<< $a->(0) >> for coordinate values on
3347 the set [-0.5,0.5], and all methods will return C<< $a->(1) >> for
3348 a coordinate value of exactly 1.
3349  
3350 Recognized options:
3351  
3352 =over 3
3353  
3354 =item method
3355  
3356 Values can be:
3357  
3358 =over 3
3359  
3360 =item * 0, s, sample, Sample (default for integer source types)
3361  
3362 The nearest value is taken. Pixels are regarded as centered on their
3363 respective integer coordinates (no offset from the linear case).
3364  
3365 =item * 1, l, linear, Linear (default for floating point source types)
3366  
3367 The values are N-linearly interpolated from an N-dimensional cube of size 2.
3368  
3369 =item * 3, c, cube, cubic, Cubic
3370  
3371 The values are interpolated using a local cubic fit to the data. The
3372 fit is constrained to match the original data and its derivative at the
3373 data points. The second derivative of the fit is not continuous at the
3374 data points. Multidimensional datasets are interpolated by the
3375 successive-collapse method.
3376  
3377 (Note that the constraint on the first derivative causes a small amount
3378 of ringing around sudden features such as step functions).
3379  
3380 =item * f, fft, fourier, Fourier
3381  
3382 The source is Fourier transformed, and the interpolated values are
3383 explicitly calculated from the coefficients. The boundary condition
3384 option is ignored -- periodic boundaries are imposed.
3385  
3386 If you pass in the option "fft", and it is a list (ARRAY) ref, then it
3387 is a stash for the magnitude and phase of the source FFT. If the list
3388 has two elements then they are taken as already computed; otherwise
3389 they are calculated and put in the stash.
3390  
3391 =back
3392  
3393 =item b, bound, boundary, Boundary
3394  
3395 This option is passed unmodified into L<indexND|PDL::Slices/indexND>,
3396 which is used as the indexing engine for the interpolation.
3397 Some current allowed values are 'extend', 'periodic', 'truncate', and 'mirror'
3398 (default is 'truncate').
3399  
3400 =item bad
3401  
3402 contains the fill value used for 'truncate' boundary. (default 0)
3403  
3404 =item fft
3405  
3406 An array ref whose associated list is used to stash the FFT of the source
3407 data, for the FFT method.
3408  
3409 =back
3410  
3411 =cut
3412  
3413 *interpND = *PDL::interpND;
3414 sub PDL::interpND {
3415 my $source = shift;
3416 my $index = shift;
3417 my $options = shift;
3418  
3419 barf 'Usage: interpND($source,$index[,{%options}])'
3420 if defined $options and ref $options ne 'HASH';
3421  
3422 my $opt = defined $options ? $options : {};
3423  
3424 my $method = $opt->{m} || $opt->{meth} || $opt->{method} || $opt->{Method};
3425 $method //= $source->type->integer ? 'sample' : 'linear';
3426  
3427 my $boundary = $opt->{b} || $opt->{boundary} || $opt->{Boundary} || $opt->{bound} || $opt->{Bound} || 'extend';
3428 my $bad = $opt->{bad} || $opt->{Bad} || 0.0;
3429  
3430 return $source->range(PDL::Math::floor($index+0.5),0,$boundary)
3431 if $method =~ m/^s(am(p(le)?)?)?/i;
3432  
3433 if (($method eq 1) || $method =~ m/^l(in(ear)?)?/i) {
3434 ## key: (ith = index broadcast; cth = cube broadcast; sth = source broadcast)
3435 my $d = $index->dim(0);
3436 my $di = $index->ndims - 1;
3437  
3438 # Grab a 2-on-a-side n-cube around each desired pixel
3439 my $samp = $source->range($index->floor,2,$boundary); # (ith, cth, sth)
3440  
3441 # Reorder to put the cube dimensions in front and convert to a list
3442 $samp = $samp->reorder( $di .. $di+$d-1,
3443 0 .. $di-1,
3444 $di+$d .. $samp->ndims-1) # (cth, ith, sth)
3445 ->clump($d); # (clst, ith, sth)
3446  
3447 # Enumerate the corners of an n-cube and convert to a list
3448 # (the 'x' is the normal perl repeat operator)
3449 my $crnr = PDL::Basic::ndcoords( (2) x $index->dim(0) ) # (index,cth)
3450 ->mv(0,-1)->clump($index->dim(0))->mv(-1,0); # (index, clst)
3451 # a & b are the weighting coefficients.
3452 my($x,$y);
3453 $index->where( 0 * $index ) .= -10; # Change NaN to invalid
3454 {
3455 my $bb = PDL::Math::floor($index);
3456 $x = ($index - $bb) -> dummy(1,$crnr->dim(1)); # index, clst, ith
3457 $y = ($bb + 1 - $index) -> dummy(1,$crnr->dim(1)); # index, clst, ith
3458 }
3459  
3460 # Use 1/0 corners to select which multiplier happens, multiply
3461 # 'em all together to get sample weights, and sum to get the answer.
3462 my $out0 = ( ($x * ($crnr==1) + $y * ($crnr==0)) #index, clst, ith
3463 -> prodover #clst, ith
3464 );
3465  
3466 my $out = ($out0 * $samp)->sumover; # ith, sth
3467  
3468 # Work around BAD-not-being-contagious bug in PDL <= 2.6 bad handling code --CED 3-April-2013
3469 if ($source->badflag) {
3470 my $baddies = $samp->isbad->orover;
3471 $out = $out->setbadif($baddies);
3472 }
3473  
3474 $out = $out->convert($source->type->enum) if $out->type != $source->type;
3475 return $out;
3476  
3477 } elsif(($method eq 3) || $method =~ m/^c(u(b(e|ic)?)?)?/i) {
3478  
3479 my ($d,@di) = $index->dims;
3480 my $di = $index->ndims - 1;
3481  
3482 # Grab a 4-on-a-side n-cube around each desired pixel
3483 my $samp = $source->range($index->floor - 1,4,$boundary) #ith, cth, sth
3484 ->reorder( $di .. $di+$d-1, 0..$di-1, $di+$d .. $source->ndims-1 );
3485 # (cth, ith, sth)
3486  
3487 # Make a cube of the subpixel offsets, and expand its dims to
3488 # a 4-on-a-side N-1 cube, to match the slices of $samp (used below).
3489 my $y = $index - $index->floor;
3490 for my $i(1..$d-1) {
3491 $y = $y->dummy($i,4);
3492 }
3493  
3494 # Collapse by interpolation, one dimension at a time...
3495 for my $i(0..$d-1) {
3496 my $a0 = $samp->slice("(1)"); # Just-under-sample
3497 my $a1 = $samp->slice("(2)"); # Just-over-sample
3498 my $a1a0 = $a1 - $a0;
3499  
3500 my $gradient = 0.5 * ($samp->slice("2:3")-$samp->slice("0:1"));
3501 my $s0 = $gradient->slice("(0)"); # Just-under-gradient
3502 my $s1 = $gradient->slice("(1)"); # Just-over-gradient
3503  
3504 my $bb = $y->slice("($i)");
3505  
3506 # Collapse the sample...
3507 $samp = ( $a0 +
3508 $bb * (
3509 $s0 +
3510 $bb * ( (3 * $a1a0 - 2*$s0 - $s1) +
3511 $bb * ( $s1 + $s0 - 2*$a1a0 )
3512 )
3513 )
3514 );
3515  
3516 # "Collapse" the subpixel offset...
3517 $y = $y->slice(":,($i)");
3518 }
3519  
3520 $samp = $samp->convert($source->type->enum) if $samp->type != $source->type;
3521 return $samp;
3522  
3523 } elsif($method =~ m/^f(ft|ourier)?/i) {
3524  
3525 require PDL::FFT;
3526 my $fftref = $opt->{fft};
3527 $fftref = [] unless(ref $fftref eq 'ARRAY');
3528 if(@$fftref != 2) {
3529 my $x = $source->copy;
3530 my $y = zeroes($source);
3531 PDL::FFT::fftnd($x,$y);
3532 $fftref->[0] = sqrt($x*$x+$y*$y) / $x->nelem;
3533 $fftref->[1] = - atan2($y,$x);
3534 }
3535  
3536 my $i;
3537 my $c = PDL::Basic::ndcoords($source); # (dim, source-dims)
3538 for $i(1..$index->ndims-1) {
3539 $c = $c->dummy($i,$index->dim($i))
3540 }
3541 my $id = $index->ndims-1;
3542 my $phase = (($c * $index * 3.14159 * 2 / pdl($source->dims))
3543 ->sumover) # (index-dims, source-dims)
3544 ->reorder($id..$id+$source->ndims-1,0..$id-1); # (src, index)
3545  
3546 my $phref = $fftref->[1]->copy; # (source-dims)
3547 my $mag = $fftref->[0]->copy; # (source-dims)
3548  
3549 for $i(1..$index->ndims-1) {
3550 $phref = $phref->dummy(-1,$index->dim($i));
3551 $mag = $mag->dummy(-1,$index->dim($i));
3552 }
3553 my $out = cos($phase + $phref ) * $mag;
3554 $out = $out->clump($source->ndims)->sumover;
3555 $out = $out->convert($source->type->enum) if $out->type != $source->type;
3556 return $out;
3557 } else {
3558 barf("interpND: unknown method '$method'; valid ones are 'linear' and 'sample'.\n");
3559 }
3560 }
3561  
3562 #line 3231 "lib/PDL/Primitive.pd"
3563  
3564 =head2 one2nd
3565  
3566 =for ref
3567  
3568 Converts a one dimensional index ndarray to a set of ND coordinates
3569  
3570 =for usage
3571  
3572 @coords=one2nd($x, $indices)
3573  
3574 returns an array of ndarrays containing the ND indexes corresponding to
3575 the one dimensional list indices. The indices are assumed to
3576 correspond to array C<$x> clumped using C<clump(-1)>. This routine is
3577 used in the old vector form of L</whichND>, but is useful on
3578 its own occasionally.
3579  
3580 Returned ndarrays have the L<indx|PDL::Core/indx> datatype. C<$indices> can have
3581 values larger than C<< $x->nelem >> but negative values in C<$indices>
3582 will not give the answer you expect.
3583  
3584 =for example
3585  
3586 pdl> $x=pdl [[[1,2],[-1,1]], [[0,-3],[3,2]]]; $c=$x->clump(-1)
3587 pdl> $maxind=maximum_ind($c); p $maxind;
3588 6
3589 pdl> print one2nd($x, maximum_ind($c))
3590 0 1 1
3591 pdl> p $x->at(0,1,1)
3592 3
3593  
3594 =cut
3595  
3596 *one2nd = \&PDL::one2nd;
3597 sub PDL::one2nd {
3598 barf "Usage: one2nd \$array, \$indices\n" if @_ != 2;
3599 my ($x, $ind)=@_;
3600 my @dimension=$x->dims;
3601 $ind = indx($ind);
3602 my(@index);
3603 my $count=0;
3604 foreach (@dimension) {
3605 $index[$count++]=$ind % $_;
3606 $ind /= $_;
3607 }
3608 return @index;
3609 }
3610 #line 3611 "lib/PDL/Primitive.pm"
3611  
3612  
3613 =head2 which
3614  
3615 =for sig
3616  
3617 Signature: (mask(n); indx [o] inds(n); indx [o]lastout())
3618 Types: (sbyte byte short ushort long ulong indx ulonglong longlong
3619 float double ldouble cfloat cdouble cldouble)
3620  
3621 =for ref
3622  
3623 Returns indices of non-zero values from a 1-D PDL
3624  
3625 =for usage
3626  
3627 $i = which($mask);
3628  
3629 returns a pdl with indices for all those elements that are nonzero in
3630 the mask. Note that the returned indices will be 1D. If you feed in a
3631 multidimensional mask, it will be flattened before the indices are
3632 calculated. See also L</whichND> for multidimensional masks.
3633  
3634 If you want to index into the original mask or a similar ndarray
3635 with output from C<which>, remember to flatten it before calling index:
3636  
3637 $data = random 5, 5;
3638 $idx = which $data > 0.5; # $idx is now 1D
3639 $bigsum = $data->flat->index($idx)->sum; # flatten before indexing
3640  
3641 Compare also L</where> for similar functionality.
3642  
3643 SEE ALSO:
3644  
3645 L</which_both> returns separately the indices of both nonzero and zero
3646 values in the mask.
3647  
3648 L</where_both> returns separately slices of both nonzero and zero
3649 values in the mask.
3650  
3651 L</where> returns associated values from a data PDL, rather than
3652 indices into the mask PDL.
3653  
3654 L</whichND> returns N-D indices into a multidimensional PDL.
3655  
3656 =for example
3657  
3658 pdl> $x = sequence(10); p $x
3659 [0 1 2 3 4 5 6 7 8 9]
3660 pdl> $indx = which($x>6); p $indx
3661 [7 8 9]
3662  
3663 =pod
3664  
3665 Broadcasts over its inputs.
3666  
3667 =for bad
3668  
3669 C<which> processes bad values.
3670 It will set the bad-value flag of all output ndarrays if the flag is set for any of the input ndarrays.
3671  
3672 =cut
3673  
3674  
3675  
3676  
3677  
3678 #line 3364 "lib/PDL/Primitive.pd"
3679 sub which { my ($this,$out) = @_;
3680 $this = $this->flat;
3681 $out //= $this->nullcreate;
3682 PDL::_which_int($this,$out,my $lastout = $this->nullcreate);
3683 my $lastoutmax = $lastout->max->sclr;
3684 $lastoutmax ? $out->slice('0:'.($lastoutmax-1))->sever : empty(indx);
3685 }
3686 *PDL::which = \&which;
3687 #line 3688 "lib/PDL/Primitive.pm"
3688  
3689 *which = \&PDL::which;
3690  
3691  
3692  
3693  
3694  
3695  
3696 =head2 which_both
3697  
3698 =for sig
3699  
3700 Signature: (mask(n); indx [o] inds(n); indx [o]notinds(n); indx [o]lastout(); indx [o]lastoutn())
3701 Types: (sbyte byte short ushort long ulong indx ulonglong longlong
3702 float double ldouble cfloat cdouble cldouble)
3703  
3704 =for ref
3705  
3706 Returns indices of nonzero and zero values in a mask PDL
3707  
3708 =for usage
3709  
3710 ($i, $c_i) = which_both($mask);
3711  
3712 This works just as L</which>, but the complement of C<$i> will be in
3713 C<$c_i>.
3714  
3715 =for example
3716  
3717 pdl> p $x = sequence(10)
3718 [0 1 2 3 4 5 6 7 8 9]
3719 pdl> ($big, $small) = which_both($x >= 5); p "$big\n$small"
3720 [5 6 7 8 9]
3721 [0 1 2 3 4]
3722  
3723 See also L</whichND_both> for the n-dimensional version.
3724  
3725 =pod
3726  
3727 Broadcasts over its inputs.
3728  
3729 =for bad
3730  
3731 C<which_both> processes bad values.
3732 It will set the bad-value flag of all output ndarrays if the flag is set for any of the input ndarrays.
3733  
3734 =cut
3735  
3736  
3737  
3738  
3739  
3740 #line 3381 "lib/PDL/Primitive.pd"
3741 sub which_both { my ($this,$outi,$outni) = @_;
3742 $this = $this->flat;
3743 $outi //= $this->nullcreate;
3744 $outni //= $this->nullcreate;
3745 PDL::_which_both_int($this,$outi,$outni,my $lastout = $this->nullcreate,my $lastoutn = $this->nullcreate);
3746 my $lastoutmax = $lastout->max->sclr;
3747 $outi = $lastoutmax ? $outi->slice('0:'.($lastoutmax-1))->sever : empty(indx);
3748 return $outi if !wantarray;
3749 my $lastoutnmax = $lastoutn->max->sclr;
3750 ($outi, $lastoutnmax ? $outni->slice('0:'.($lastoutnmax-1))->sever : empty(indx));
3751 }
3752 *PDL::which_both = \&which_both;
3753 #line 3754 "lib/PDL/Primitive.pm"
3754  
3755 *which_both = \&PDL::which_both;
3756  
3757  
3758  
3759  
3760  
3761  
3762 =head2 whichover
3763  
3764 =for sig
3765  
3766 Signature: (a(n); [o]o(n))
3767 Types: (sbyte byte short ushort long ulong indx ulonglong longlong
3768 float double ldouble cfloat cdouble cldouble)
3769  
3770 =for usage
3771  
3772 $o = whichover($a);
3773 whichover($a, $o); # all arguments given
3774 $o = $a->whichover; # method call
3775 $a->whichover($o);
3776 $a->inplace->whichover; # can be used inplace
3777 whichover($a->inplace);
3778  
3779 =for ref
3780  
3781 Collects the coordinates of non-zero, non-bad values in each 1D mask in
3782 ndarray at the start of the output, and fills the rest with -1.
3783  
3784 By using L<PDL::Slices/xchg> etc. it is possible to use I<any> dimension.
3785  
3786 =for example
3787  
3788 my $a = pdl q[3 4 2 3 2 3 1];
3789 my $b = $a->uniq;
3790 my $c = +($a->dummy(0) == $b)->transpose;
3791 print $c, $c->whichover;
3792 # [
3793 # [0 0 0 0 0 0 1]
3794 # [0 0 1 0 1 0 0]
3795 # [1 0 0 1 0 1 0]
3796 # [0 1 0 0 0 0 0]
3797 # ]
3798 # [
3799 # [ 6 -1 -1 -1 -1 -1 -1]
3800 # [ 2 4 -1 -1 -1 -1 -1]
3801 # [ 0 3 5 -1 -1 -1 -1]
3802 # [ 1 -1 -1 -1 -1 -1 -1]
3803 # ]
3804  
3805 =pod
3806  
3807 Can operate inplace with C<a> as output C<o>.
3808 Broadcasts over its inputs.
3809  
3810 =for bad
3811  
3812 C<whichover> processes bad values.
3813 It will set the bad-value flag of all output ndarrays if the flag is set for any of the input ndarrays.
3814  
3815 =cut
3816  
3817  
3818  
3819  
3820 *whichover = \&PDL::whichover;
3821  
3822  
3823  
3824  
3825  
3826  
3827 =head2 approx_artol
3828  
3829 =for sig
3830  
3831 Signature: (got(); expected(); sbyte [o] result(); double atol; double rtol)
3832 Types: (sbyte byte short ushort long ulong indx ulonglong longlong
3833 float double ldouble cfloat cdouble cldouble)
3834  
3835 =for usage
3836  
3837 $result = approx_artol($got, $expected); # using defaults of atol=1e-06, rtol=0
3838 $result = approx_artol($got, $expected, $atol);
3839 $result = approx_artol($got, $expected, $atol, $rtol);
3840 approx_artol($got, $expected, $atol, $rtol, $result); # all arguments given
3841 $result = $got->approx_artol($expected); # method call
3842 $result = $got->approx_artol($expected, $atol);
3843 $result = $got->approx_artol($expected, $atol, $rtol);
3844 $got->approx_artol($expected, $atol, $rtol, $result);
3845  
3846 =for ref
3847  
3848 Returns C<sbyte> mask whether C<< abs($got()-$expected())> <= >> either
3849 absolute or relative (C<rtol> * C<$expected()>) tolerances.
3850  
3851 Relative tolerance defaults to zero, and absolute tolerance defaults to
3852 C<1e-6>, for compatibility with L<PDL::Core/approx>.
3853  
3854 Works with complex numbers, and to avoid expensive C<sqrt>ing uses the
3855 squares of the input quantities and differences. Bear this in mind for
3856 numbers outside the range (for C<double>) of about C<1e-154..1e154>.
3857  
3858 Handles C<NaN>s by showing them approximately equal (i.e. true in the
3859 output) if both values are C<NaN>, and not otherwise.
3860  
3861 Adapted from code by Edward Baudrez, test changed from C<< < >> to C<< <= >>.
3862  
3863 =pod
3864  
3865 Broadcasts over its inputs.
3866  
3867 =for bad
3868  
3869 Handles bad values similarly to C<NaN>s, above. This includes if only
3870 one of the two input ndarrays has their badflag true.
3871  
3872 =cut
3873  
3874  
3875  
3876  
3877 *approx_artol = \&PDL::approx_artol;
3878  
3879  
3880  
3881  
3882  
3883 #line 3513 "lib/PDL/Primitive.pd"
3884  
3885 =head2 where
3886  
3887 =for ref
3888  
3889 Use a mask to select values from one or more data PDLs
3890  
3891 C<where> accepts one or more data ndarrays and a mask ndarray. It
3892 returns a list of output ndarrays, corresponding to the input data
3893 ndarrays. Each output ndarray is a 1-dimensional list of values in its
3894 corresponding data ndarray. The values are drawn from locations where
3895 the mask is nonzero.
3896  
3897 The output PDLs are still connected to the original data PDLs, for the
3898 purpose of dataflow.
3899  
3900 C<where> combines the functionality of L</which> and L<index|PDL::Slices/index>
3901 into a single operation.
3902  
3903 BUGS:
3904  
3905 While C<where> works OK for most N-dimensional cases, it does not
3906 broadcast properly over (for example) the (N+1)th dimension in data
3907 that is compared to an N-dimensional mask. Use C<whereND> for that.
3908  
3909 =for example
3910  
3911 $i = $x->where($x+5 > 0); # $i contains those elements of $x
3912 # where mask ($x+5 > 0) is 1
3913 $i .= -5; # Set those elements (of $x) to -5. Together, these
3914 # commands clamp $x to a maximum of -5.
3915  
3916 It is also possible to use the same mask for several ndarrays with
3917 the same call:
3918  
3919 ($i,$j,$k) = where($x,$y,$z, $x+5>0);
3920  
3921 Note: C<$i> is always 1-D, even if C<$x> is E<gt>1-D.
3922  
3923 WARNING: The first argument
3924 (the values) and the second argument (the mask) currently have to have
3925 the exact same dimensions (or horrible things happen). You *cannot*
3926 broadcast over a smaller mask, for example.
3927  
3928 =cut
3929  
3930 sub PDL::where :lvalue {
3931 barf "Usage: where( \$pdl1, ..., \$pdlN, \$mask )\n" if @_ == 1;
3932 my $mask = pop->flat->which;
3933 @_ == 1 ? $_[0]->flat->index($mask) : map $_->flat->index($mask), @_;
3934 }
3935 *where = \&PDL::where;
3936  
3937 #line 3569 "lib/PDL/Primitive.pd"
3938  
3939 =head2 where_both
3940  
3941 =for ref
3942  
3943 Returns slices (non-zero in mask, zero) of an ndarray according to a mask
3944  
3945 =for usage
3946  
3947 ($match_vals, $non_match_vals) = where_both($pdl, $mask);
3948  
3949 This works like L</which_both>, but (flattened) data-flowing slices
3950 rather than index-sets are returned.
3951  
3952 =for example
3953  
3954 pdl> p $x = sequence(10) + 2
3955 [2 3 4 5 6 7 8 9 10 11]
3956 pdl> ($big, $small) = where_both($x, $x > 5); p "$big\n$small"
3957 [6 7 8 9 10 11]
3958 [2 3 4 5]
3959 pdl> p $big += 2, $small -= 1
3960 [8 9 10 11 12 13] [1 2 3 4]
3961 pdl> p $x
3962 [1 2 3 4 8 9 10 11 12 13]
3963  
3964 =cut
3965  
3966 sub PDL::where_both {
3967 barf "Usage: where_both(\$pdl, \$mask)\n" if @_ != 2;
3968 my ($arr, $mask) = @_; # $mask has 0==false, 1==true
3969 my $arr_flat = $arr->flat;
3970 map $arr_flat->index1d($_), PDL::which_both($mask);
3971 }
3972 *where_both = \&PDL::where_both;
3973  
3974 #line 3607 "lib/PDL/Primitive.pd"
3975  
3976 =head2 whereND
3977  
3978 =for ref
3979  
3980 C<where> with support for ND masks and broadcasting
3981  
3982 C<whereND> accepts one or more data ndarrays and a
3983 mask ndarray. It returns a list of output ndarrays,
3984 corresponding to the input data ndarrays. The values
3985 are drawn from locations where the mask is nonzero.
3986  
3987 C<whereND> differs from C<where> in that the mask
3988 dimensionality is preserved which allows for
3989 proper broadcasting of the selection operation over
3990 higher dimensions.
3991  
3992 As with C<where> the output PDLs are still connected
3993 to the original data PDLs, for the purpose of dataflow.
3994  
3995 =for usage
3996  
3997 $sdata = whereND $data, $mask
3998 ($s1, $s2, ..., $sn) = whereND $d1, $d2, ..., $dn, $mask
3999  
4000 where
4001  
4002 $data is M dimensional
4003 $mask is N < M dimensional
4004 dims($data) 1..N == dims($mask) 1..N
4005 with broadcasting over N+1 to M dimensions
4006  
4007 =for example
4008  
4009 $data = sequence(4,3,2); # example data array
4010 $mask4 = (random(4)>0.5); # example 1-D mask array, has $n4 true values
4011 $mask43 = (random(4,3)>0.5); # example 2-D mask array, has $n43 true values
4012 $sdat4 = whereND $data, $mask4; # $sdat4 is a [$n4,3,2] pdl
4013 $sdat43 = whereND $data, $mask43; # $sdat43 is a [$n43,2] pdl
4014  
4015 Just as with C<where>, you can use the returned value in an
4016 assignment. That means that both of these examples are valid:
4017  
4018 # Used to create a new slice stored in $sdat4:
4019 $sdat4 = $data->whereND($mask4);
4020 $sdat4 .= 0;
4021 # Used in lvalue context:
4022 $data->whereND($mask4) .= 0;
4023  
4024 SEE ALSO:
4025  
4026 L</whichND> returns N-D indices into a multidimensional PDL, from a mask.
4027  
4028 =cut
4029  
4030 sub PDL::whereND :lvalue {
4031 barf "Usage: whereND( \$pdl1, ..., \$pdlN, \$mask )\n" if @_ == 1;
4032 my $mask = pop @_; # $mask has 0==false, 1==true
4033 my @to_return;
4034 my $n = PDL::sum($mask);
4035 my $maskndims = $mask->ndims;
4036 foreach my $arr (@_) {
4037 # count the number of dims in $mask and $arr
4038 # $mask = a b c d e f.....
4039 my @idims = dims($arr);
4040 splice @idims, 0, $maskndims; # pop off the number of dims in $mask
4041 if (!$n or $arr->isempty) {
4042 push @to_return, PDL->zeroes($arr->type, $n, @idims);
4043 next;
4044 }
4045 my $sub_i = $mask * ones($arr);
4046 my $where_sub_i = PDL::where($arr, $sub_i);
4047 my $ndim = 0;
4048 foreach my $id ($n, @idims[0..($#idims-1)]) {
4049 $where_sub_i = $where_sub_i->splitdim($ndim++,$id) if $n>0;
4050 }
4051 push @to_return, $where_sub_i;
4052 }
4053 return (@to_return == 1) ? $to_return[0] : @to_return;
4054 }
4055 *whereND = \&PDL::whereND;
4056  
4057 =head2 whereND_both
4058  
4059 =for ref
4060  
4061 C<where_both> with support for ND masks and broadcasting
4062  
4063 This works like L</whichND_both>, but data-flowing slices
4064 rather than index-sets are returned.
4065  
4066 C<whereND_both> differs from C<where_both> in that the mask
4067 dimensionality is preserved which allows for
4068 proper broadcasting of the selection operation over
4069 higher dimensions.
4070  
4071 As with C<where_both> the output PDLs are still connected
4072 to the original data PDLs, for the purpose of dataflow.
4073  
4074 =for usage
4075  
4076 ($match_vals, $non_match_vals) = whereND_both($pdl, $mask);
4077  
4078 =cut
4079  
4080 sub PDL::whereND_both :lvalue {
4081 barf "Usage: whereND_both(\$pdl, \$mask)\n" if @_ != 2;
4082 my ($arr, $mask) = @_; # $mask has 0==false, 1==true
4083 map $arr->indexND($_), PDL::whichND_both($mask);
4084 }
4085 *whereND_both = \&PDL::whereND_both;
4086  
4087 #line 3721 "lib/PDL/Primitive.pd"
4088  
4089 =head2 whichND
4090  
4091 =for ref
4092  
4093 Return the coordinates of non-zero values in a mask.
4094  
4095 =for usage
4096  
4097 WhichND returns the N-dimensional coordinates of each nonzero value in
4098 a mask PDL with any number of dimensions. The returned values arrive
4099 as an array-of-vectors suitable for use in
4100 L<indexND|PDL::Slices/indexND> or L<range|PDL::Slices/range>.
4101  
4102 $coords = whichND($mask);
4103  
4104 returns a PDL containing the coordinates of the elements that are non-zero
4105 in C<$mask>, suitable for use in L<PDL::Slices/indexND>. The 0th dimension contains the
4106 full coordinate listing of each point; the 1st dimension lists all the points.
4107 For example, if $mask has rank 4 and 100 matching elements, then $coords has
4108 dimension 4x100.
4109  
4110 If no such elements exist, then whichND returns a structured empty PDL:
4111 an Nx0 PDL that contains no values (but matches, broadcasting-wise, with
4112 the vectors that would be produced if such elements existed).
4113  
4114 DEPRECATED BEHAVIOR IN LIST CONTEXT:
4115  
4116 whichND once delivered different values in list context than in scalar
4117 context, for historical reasons. In list context, it returned the
4118 coordinates transposed, as a collection of 1-PDLs (one per dimension)
4119 in a list. This usage is deprecated in PDL 2.4.10, and will cause a
4120 warning to be issued every time it is encountered. To avoid the
4121 warning, you can set the global variable "$PDL::whichND" to 's' to
4122 get scalar behavior in all contexts, or to 'l' to get list behavior in
4123 list context.
4124  
4125 In later versions of PDL, the deprecated behavior will disappear. Deprecated
4126 list context whichND expressions can be replaced with:
4127  
4128 @list = $x->whichND->mv(0,-1)->dog;
4129  
4130 SEE ALSO:
4131  
4132 L</which> finds coordinates of nonzero values in a 1-D mask.
4133  
4134 L</where> extracts values from a data PDL that are associated
4135 with nonzero values in a mask PDL.
4136  
4137 L<PDL::Slices/indexND> can be fed the coordinates to return the values.
4138  
4139 =for example
4140  
4141 pdl> $s=sequence(10,10,3,4)
4142 pdl> ($x, $y, $z, $w)=whichND($s == 203); p $x, $y, $z, $w
4143 [3] [0] [2] [0]
4144 pdl> print $s->at(list(cat($x,$y,$z,$w)))
4145 203
4146  
4147 =cut
4148  
4149 sub _one2nd {
4150 my ($mask, $ind) = @_;
4151 my $ndims = my @mdims = $mask->dims;
4152 # In the empty case, explicitly return the correct type of structured empty
4153 return PDL->new_from_specification(indx, $ndims, 0) if !$ind->nelem;
4154 my $mult = ones(indx, $ndims);
4155 $mult->index($_+1) .= $mult->index($_) * $mdims[$_] for 0..$#mdims-1;
4156 for my $i (0..$#mdims) {
4157 my $s = $ind->index($i);
4158 $s /= $mult->index($i);
4159 $s %= $mdims[$i];
4160 }
4161 $ind;
4162 }
4163  
4164 *whichND = \&PDL::whichND;
4165 sub PDL::whichND {
4166 my $mask = PDL->topdl(shift);
4167  
4168 # List context: generate a perl list by dimension
4169 if(wantarray) {
4170 if(!defined($PDL::whichND)) {
4171 printf STDERR "whichND: WARNING - list context deprecated. Set \$PDL::whichND. Details in pod.";
4172 } elsif($PDL::whichND =~ m/l/i) {
4173 # old list context enabled by setting $PDL::whichND to 'l'
4174 return $mask->one2nd($mask->flat->which);
4175 }
4176 # if $PDL::whichND does not contain 'l' or 'L', fall through to scalar context
4177 }
4178  
4179 # Scalar context: generate an N-D index ndarray
4180 my $ndims = $mask->getndims;
4181 return PDL->new_from_specification(indx,$ndims,0) if !$mask->nelem;
4182 return $mask ? pdl(indx,0) : PDL->new_from_specification(indx,0) if !$ndims;
4183 _one2nd($mask, $mask->flat->which->dummy(0,$ndims)->sever);
4184 }
4185  
4186 =head2 whichND_both
4187  
4188 =for ref
4189  
4190 Return the coordinates of non-zero values in a mask.
4191  
4192 =for usage
4193  
4194 Like L</which_both>, but returns the N-dimensional coordinates (like
4195 L</whichND>) of the nonzero, zero values in the mask PDL. The
4196 returned values arrive as an array-of-vectors suitable for use in
4197 L<indexND|PDL::Slices/indexND> or L<range|PDL::Slices/range>.
4198 Added in 2.099.
4199  
4200 ($nonzero_coords, $zero_coords) = whichND_both($mask);
4201  
4202 SEE ALSO:
4203  
4204 L</which> finds coordinates of nonzero values in a 1-D mask.
4205  
4206 L</where> extracts values from a data PDL that are associated
4207 with nonzero values in a mask PDL.
4208  
4209 L<PDL::Slices/indexND> can be fed the coordinates to return the values.
4210  
4211 =for example
4212  
4213 pdl> $s=sequence(10,10,3,4)
4214 pdl> ($x, $y, $z, $w)=whichND($s == 203); p $x, $y, $z, $w
4215 [3] [0] [2] [0]
4216 pdl> print $s->at(list(cat($x,$y,$z,$w)))
4217 203
4218  
4219 =cut
4220  
4221 *whichND_both = \&PDL::whichND_both;
4222 sub PDL::whichND_both {
4223 my $mask = PDL->topdl(shift);
4224 return ((PDL->new_from_specification(indx,$mask->ndims,0))x2) if !$mask->nelem;
4225 my $ndims = $mask->getndims;
4226 if (!$ndims) {
4227 my ($t, $f) = (pdl(indx,0), PDL->new_from_specification(indx,0));
4228 return $mask ? ($t,$f) : ($f,$t);
4229 }
4230 map _one2nd($mask, $_->dummy(0,$ndims)->sever), $mask->flat->which_both;
4231 }
4232  
4233 #line 3872 "lib/PDL/Primitive.pd"
4234  
4235 =head2 setops
4236  
4237 =for ref
4238  
4239 Implements simple set operations like union and intersection
4240  
4241 =for usage
4242  
4243 Usage: $set = setops($x, <OPERATOR>, $y);
4244  
4245 The operator can be C<OR>, C<XOR> or C<AND>. This is then applied
4246 to C<$x> viewed as a set and C<$y> viewed as a set. Set theory says
4247 that a set may not have two or more identical elements, but setops
4248 takes care of this for you, so C<$x=pdl(1,1,2)> is OK. The functioning
4249 is as follows:
4250  
4251 =over
4252  
4253 =item C<OR>
4254  
4255 The resulting vector will contain the elements that are either in C<$x>
4256 I<or> in C<$y> or both. This is the union in set operation terms
4257  
4258 =item C<XOR>
4259  
4260 The resulting vector will contain the elements that are either in C<$x>
4261 or C<$y>, but not in both. This is
4262  
4263 Union($x, $y) - Intersection($x, $y)
4264  
4265 in set operation terms.
4266  
4267 =item C<AND>
4268  
4269 The resulting vector will contain the intersection of C<$x> and C<$y>, so
4270 the elements that are in both C<$x> and C<$y>. Note that for convenience
4271 this operation is also aliased to L</intersect>.
4272  
4273 =back
4274  
4275 It should be emphasized that these routines are used when one or both of
4276 the sets C<$x>, C<$y> are hard to calculate or that you get from a separate
4277 subroutine.
4278  
4279 Finally IDL users might be familiar with Craig Markwardt's C<cmset_op.pro>
4280 routine which has inspired this routine although it was written independently
4281 However the present routine has a few less options (but see the examples)
4282  
4283 =for example
4284  
4285 You will very often use these functions on an index vector, so that is
4286 what we will show here. We will in fact something slightly silly. First
4287 we will find all squares that are also cubes below 10000.
4288  
4289 Create a sequence vector:
4290  
4291 pdl> $x = sequence(10000)
4292  
4293 Find all odd and even elements:
4294  
4295 pdl> ($even, $odd) = which_both( ($x % 2) == 0)
4296  
4297 Find all squares
4298  
4299 pdl> $squares= which(ceil(sqrt($x)) == floor(sqrt($x)))
4300  
4301 Find all cubes (being careful with roundoff error!)
4302  
4303 pdl> $cubes= which(ceil($x**(1.0/3.0)) == floor($x**(1.0/3.0)+1e-6))
4304  
4305 Then find all squares that are cubes:
4306  
4307 pdl> $both = setops($squares, 'AND', $cubes)
4308  
4309 And print these (assumes that C<PDL::NiceSlice> is loaded!)
4310  
4311 pdl> p $x($both)
4312 [0 1 64 729 4096]
4313  
4314 Then find all numbers that are either cubes or squares, but not both:
4315  
4316 pdl> $cube_xor_square = setops($squares, 'XOR', $cubes)
4317  
4318 pdl> p $cube_xor_square->nelem()
4319 112
4320  
4321 So there are a total of 112 of these!
4322  
4323 Finally find all odd squares:
4324  
4325 pdl> $odd_squares = setops($squares, 'AND', $odd)
4326  
4327 Another common occurrence is to want to get all objects that are
4328 in C<$x> and in the complement of C<$y>. But it is almost always best
4329 to create the complement explicitly since the universe that both are
4330 taken from is not known. Thus use L</which_both> if possible
4331 to keep track of complements.
4332  
4333 If this is impossible the best approach is to make a temporary:
4334  
4335 This creates an index vector the size of the universe of the sets and
4336 set all elements in C<$y> to 0
4337  
4338 pdl> $tmp = ones($n_universe); $tmp($y) .= 0;
4339  
4340 This then finds the complement of C<$y>
4341  
4342 pdl> $C_b = which($tmp == 1);
4343  
4344 and this does the final selection:
4345  
4346 pdl> $set = setops($x, 'AND', $C_b)
4347  
4348 =cut
4349  
4350 *setops = \&PDL::setops;
4351  
4352 sub PDL::setops {
4353  
4354 my ($x, $op, $y)=@_;
4355  
4356 # Check that $x and $y are 1D.
4357 if ($x->ndims() > 1 || $y->ndims() > 1) {
4358 warn 'setops: $x and $y must be 1D - flattening them!'."\n";
4359 $x = $x->flat;
4360 $y = $y->flat;
4361 }
4362  
4363 #Make sure there are no duplicate elements.
4364 $x=$x->uniq;
4365 $y=$y->uniq;
4366  
4367 my $result;
4368  
4369 if ($op eq 'OR') {
4370 # Easy...
4371 $result = uniq(append($x, $y));
4372 } elsif ($op eq 'XOR') {
4373 # Make ordered list of set union.
4374 my $union = append($x, $y)->qsort;
4375 # Index lists.
4376 my $s1=zeroes(byte, $union->nelem());
4377 my $s2=zeroes(byte, $union->nelem());
4378  
4379 # Find indices which are duplicated - these are to be excluded
4380 #
4381 # We do this by comparing x with x shifted each way.
4382 my $i1 = which($union != rotate($union, 1));
4383 my $i2 = which($union != rotate($union, -1));
4384 #
4385 # We then mark/mask these in the s1 and s2 arrays to indicate which ones
4386 # are not equal to their neighbours.
4387 #
4388 my $ts;
4389 ($ts = $s1->index($i1)) .= byte(1) if $i1->nelem() > 0;
4390 ($ts = $s2->index($i2)) .= byte(1) if $i2->nelem() > 0;
4391  
4392 my $inds=which($s1 == $s2);
4393  
4394 if ($inds->nelem() > 0) {
4395 return $union->index($inds);
4396 } else {
4397 return $inds;
4398 }
4399  
4400 } elsif ($op eq 'AND') {
4401 # The intersection of the arrays.
4402 return $x if $x->isempty;
4403 return $y if $y->isempty;
4404 # Make ordered list of set union.
4405 my $union = append($x, $y)->qsort;
4406 return $union->where($union == rotate($union, -1))->uniq;
4407 } else {
4408 print "The operation $op is not known!";
4409 return -1;
4410 }
4411  
4412 }
4413  
4414 #line 4055 "lib/PDL/Primitive.pd"
4415  
4416 =head2 intersect
4417  
4418 =for ref
4419  
4420 Calculate the intersection of two ndarrays
4421  
4422 =for usage
4423  
4424 Usage: $set = intersect($x, $y);
4425  
4426 This routine is merely a simple interface to L</setops>. See
4427 that for more information
4428  
4429 =for example
4430  
4431 Find all numbers less that 100 that are of the form 2*y and 3*x
4432  
4433 pdl> $x=sequence(100)
4434 pdl> $factor2 = which( ($x % 2) == 0)
4435 pdl> $factor3 = which( ($x % 3) == 0)
4436 pdl> $ii=intersect($factor2, $factor3)
4437 pdl> p $x($ii)
4438 [0 6 12 18 24 30 36 42 48 54 60 66 72 78 84 90 96]
4439  
4440 =cut
4441  
4442 *intersect = \&PDL::intersect;
4443  
4444 sub PDL::intersect { setops($_[0], 'AND', $_[1]) }
4445 #line 4446 "lib/PDL/Primitive.pm"
4446  
4447  
4448 =head2 pchip_chim
4449  
4450 =for sig
4451  
4452 Signature: (x(n); f(n); [o]d(n); indx [o]ierr())
4453 Types: (sbyte byte short ushort long ulong indx ulonglong longlong
4454 float double ldouble)
4455  
4456 =for usage
4457  
4458 ($d, $ierr) = pchip_chim($x, $f);
4459 pchip_chim($x, $f, $d, $ierr); # all arguments given
4460 ($d, $ierr) = $x->pchip_chim($f); # method call
4461 $x->pchip_chim($f, $d, $ierr);
4462  
4463 =for ref
4464  
4465 Calculate the derivatives of (x,f(x)) using cubic Hermite interpolation.
4466  
4467 Calculate the derivatives needed to determine a monotone piecewise
4468 cubic Hermite interpolant to the given set of points (C<$x,$f>,
4469 where C<$x> is strictly increasing).
4470 The resulting set of points - C<$x,$f,$d>, referred to
4471 as the cubic Hermite representation - can then be used in
4472 other functions, such as L</pchip_chfe>, L</pchip_chfd>,
4473 and L</pchip_chia>.
4474  
4475 The boundary conditions are compatible with monotonicity,
4476 and if the data are only piecewise monotonic, the interpolant
4477 will have an extremum at the switch points; for more control
4478 over these issues use L</pchip_chic>.
4479  
4480 References:
4481  
4482 1. F. N. Fritsch and J. Butland, A method for constructing
4483 local monotone piecewise cubic interpolants, SIAM
4484 Journal on Scientific and Statistical Computing 5, 2
4485 (June 1984), pp. 300-304.
4486  
4487 F. N. Fritsch and R. E. Carlson, Monotone piecewise
4488 cubic interpolation, SIAM Journal on Numerical Analysis
4489 17, 2 (April 1980), pp. 238-246.
4490  
4491 =pod
4492  
4493 =head3 Parameters
4494  
4495 =over
4496  
4497 =item x
4498  
4499 ordinate data
4500  
4501 =item f
4502  
4503 array of dependent variable values to be
4504 interpolated. F(I) is value corresponding to
4505 X(I). C<pchip_chim> is designed for monotonic data, but it will
4506 work for any F-array. It will force extrema at points where
4507 monotonicity switches direction. If some other treatment of
4508 switch points is desired, DPCHIC should be used instead.
4509  
4510 =item d
4511  
4512 array of derivative values at the data
4513 points. If the data are monotonic, these values will
4514 determine a monotone cubic Hermite function.
4515  
4516 =item ierr
4517  
4518 Error status:
4519  
4520 =over
4521  
4522 =item *
4523  
4524 0 if successful.
4525  
4526 =item *
4527  
4528 E<gt> 0 if there were C<ierr> switches in the direction of
4529 monotonicity (data still valid).
4530  
4531 =item *
4532  
4533 -1 if C<dim($x, 0) E<lt> 2>.
4534  
4535 =item *
4536  
4537 -3 if C<$x> is not strictly increasing.
4538  
4539 =back
4540  
4541 (The D-array has not been changed in any of these cases.)
4542 NOTE: The above errors are checked in the order listed,
4543 and following arguments have B<NOT> been validated.
4544  
4545 =back
4546  
4547 Broadcasts over its inputs.
4548  
4549 =for bad
4550  
4551 C<pchip_chim> does not process bad values.
4552 It will set the bad-value flag of all output ndarrays if the flag is set for any of the input ndarrays.
4553  
4554 =cut
4555  
4556  
4557  
4558  
4559 *pchip_chim = \&PDL::pchip_chim;
4560  
4561  
4562  
4563  
4564  
4565  
4566 =head2 pchip_chic
4567  
4568 =for sig
4569  
4570 Signature: (sbyte ic(two=2); vc(two=2); mflag(); x(n); f(n);
4571 [o]d(n); indx [o]ierr();
4572 [t]h(nless1=CALC($SIZE(n)-1)); [t]slope(nless1);)
4573 Types: (float double ldouble)
4574  
4575 =for usage
4576  
4577 ($d, $ierr) = pchip_chic($ic, $vc, $mflag, $x, $f);
4578 pchip_chic($ic, $vc, $mflag, $x, $f, $d, $ierr); # all arguments given
4579 ($d, $ierr) = $ic->pchip_chic($vc, $mflag, $x, $f); # method call
4580 $ic->pchip_chic($vc, $mflag, $x, $f, $d, $ierr);
4581  
4582 =for ref
4583  
4584 Set derivatives needed to determine a piecewise monotone piecewise
4585 cubic Hermite interpolant to given data. User control is available
4586 over boundary conditions and/or treatment of points where monotonicity
4587 switches direction.
4588  
4589 Calculate the derivatives needed to determine a piecewise monotone piecewise
4590 cubic interpolant to the data given in (C<$x,$f>,
4591 where C<$x> is strictly increasing).
4592 Control over the boundary conditions is given by the
4593 C<$ic> and C<$vc> ndarrays, and the value of C<$mflag> determines
4594 the treatment of points where monotonicity switches
4595 direction. A simpler, more restricted, interface is available
4596 using L</pchip_chim>.
4597 The resulting piecewise cubic Hermite function may be evaluated
4598 by L</pchip_chfe> or L</pchip_chfd>.
4599  
4600 References:
4601  
4602 1. F. N. Fritsch, Piecewise Cubic Hermite Interpolation
4603 Package, Report UCRL-87285, Lawrence Livermore National
4604 Laboratory, July 1982. [Poster presented at the
4605 SIAM 30th Anniversary Meeting, 19-23 July 1982.]
4606  
4607 2. F. N. Fritsch and J. Butland, A method for constructing
4608 local monotone piecewise cubic interpolants, SIAM
4609 Journal on Scientific and Statistical Computing 5, 2
4610 (June 1984), pp. 300-304.
4611  
4612 3. F. N. Fritsch and R. E. Carlson, Monotone piecewise
4613 cubic interpolation, SIAM Journal on Numerical
4614 Analysis 17, 2 (April 1980), pp. 238-246.
4615  
4616 =pod
4617  
4618 =head3 Parameters
4619  
4620 =over
4621  
4622 =item ic
4623  
4624 The first and second elements of C<$ic> determine the boundary
4625 conditions at the start and end of the data respectively.
4626 If the value is 0, then the default condition, as used by
4627 L</pchip_chim>, is adopted.
4628 If greater than zero, no adjustment for monotonicity is made,
4629 otherwise if less than zero the derivative will be adjusted.
4630 The allowed magnitudes for C<ic(0)> are:
4631  
4632 =over
4633  
4634 =item *
4635  
4636 1 if first derivative at C<x(0)> is given in C<vc(0)>.
4637  
4638 =item *
4639  
4640 2 if second derivative at C<x(0)> is given in C<vc(0)>.
4641  
4642 =item *
4643  
4644 3 to use the 3-point difference formula for C<d(0)>.
4645 (Reverts to the default b.c. if C<n E<lt> 3>)
4646  
4647 =item *
4648  
4649 4 to use the 4-point difference formula for C<d(0)>.
4650 (Reverts to the default b.c. if C<n E<lt> 4>)
4651  
4652 =item *
4653  
4654 5 to set C<d(0)> so that the second derivative is
4655 continuous at C<x(1)>.
4656 (Reverts to the default b.c. if C<n E<lt> 4>)
4657 This option is somewhat analogous to the "not a knot"
4658 boundary condition provided by DPCHSP.
4659  
4660 =back
4661  
4662 The values for C<ic(1)> are the same as above, except that
4663 the first-derivative value is stored in C<vc(1)> for cases 1 and 2.
4664 The values of C<$vc> need only be set if options 1 or 2 are chosen
4665 for C<$ic>. NOTES:
4666  
4667 =over
4668  
4669 =item *
4670  
4671 Only in case C<$ic(n)> E<lt> 0 is it guaranteed that the interpolant
4672 will be monotonic in the first interval. If the returned value of
4673 D(start_or_end) lies between zero and 3*SLOPE(start_or_end), the
4674 interpolant will be monotonic. This is B<NOT> checked if C<$ic(n)>
4675 E<gt> 0.
4676  
4677 =item *
4678  
4679 If C<$ic(n)> E<lt> 0 and D(0) had to be changed to achieve monotonicity,
4680 a warning error is returned.
4681  
4682 =back
4683  
4684 Set C<$mflag = 0> if interpolant is required to be monotonic in
4685 each interval, regardless of monotonicity of data. This causes C<$d> to be
4686 set to 0 at all switch points. NOTES:
4687  
4688 =over
4689  
4690 =item *
4691  
4692 This will cause D to be set to zero at all switch points, thus
4693 forcing extrema there.
4694  
4695 =item *
4696  
4697 The result of using this option with the default boundary conditions
4698 will be identical to using DPCHIM, but will generally cost more
4699 compute time. This option is provided only to facilitate comparison
4700 of different switch and/or boundary conditions.
4701  
4702 =back
4703  
4704 =item vc
4705  
4706 See ic for details
4707  
4708 =item mflag
4709  
4710 Set to non-zero to
4711 use a formula based on the 3-point difference formula at switch
4712 points. If C<$mflag E<gt> 0>, then the interpolant at switch points
4713 is forced to not deviate from the data by more than C<$mflag*dfloc>,
4714 where C<dfloc> is the maximum of the change of C<$f> on this interval
4715 and its two immediate neighbours.
4716 If C<$mflag E<lt> 0>, no such control is to be imposed.
4717  
4718 =item x
4719  
4720 array of independent variable values. The
4721 elements of X must be strictly increasing:
4722  
4723 X(I-1) .LT. X(I), I = 2(1)N.
4724  
4725 (Error return if not.)
4726  
4727 =item f
4728  
4729 array of dependent variable values to be
4730 interpolated. F(I) is value corresponding to X(I).
4731  
4732 =item d
4733  
4734 array of derivative values at the data
4735 points. These values will determine a monotone cubic
4736 Hermite function on each subinterval on which the data
4737 are monotonic, except possibly adjacent to switches in
4738 monotonicity. The value corresponding to X(I) is stored in D(I).
4739 No other entries in D are changed.
4740  
4741 =item ierr
4742  
4743 Error status:
4744  
4745 =over
4746  
4747 =item *
4748  
4749 0 if successful.
4750  
4751 =item *
4752  
4753 1 if C<ic(0) E<lt> 0> and C<d(0)> had to be adjusted for
4754 monotonicity.
4755  
4756 =item *
4757  
4758 2 if C<ic(1) E<lt> 0> and C<d(n-1)> had to be adjusted
4759 for monotonicity.
4760  
4761 =item *
4762  
4763 3 if both 1 and 2 are true.
4764  
4765 =item *
4766  
4767 -1 if C<n E<lt> 2>.
4768  
4769 =item *
4770  
4771 -3 if C<$x> is not strictly increasing.
4772  
4773 =item *
4774  
4775 -4 if C<abs(ic(0)) E<gt> 5>.
4776  
4777 =item *
4778  
4779 -5 if C<abs(ic(1)) E<gt> 5>.
4780  
4781 =item *
4782  
4783 -6 if both -4 and -5 are true.
4784  
4785 =item *
4786  
4787 -7 if C<nwk E<lt> 2*(n-1)>.
4788  
4789 =back
4790  
4791 (The D-array has not been changed in any of these cases.)
4792 NOTE: The above errors are checked in the order listed,
4793 and following arguments have B<NOT> been validated.
4794  
4795 =back
4796  
4797 Broadcasts over its inputs.
4798  
4799 =for bad
4800  
4801 C<pchip_chic> does not process bad values.
4802 It will set the bad-value flag of all output ndarrays if the flag is set for any of the input ndarrays.
4803  
4804 =cut
4805  
4806  
4807  
4808  
4809 *pchip_chic = \&PDL::pchip_chic;
4810  
4811  
4812  
4813  
4814  
4815  
4816 =head2 pchip_chsp
4817  
4818 =for sig
4819  
4820 Signature: (sbyte ic(two=2); vc(two=2); x(n); f(n);
4821 [o]d(n); indx [o]ierr();
4822 [t]dx(n); [t]dy_dx(n);
4823 )
4824 Types: (float double ldouble)
4825  
4826 =for usage
4827  
4828 ($d, $ierr) = pchip_chsp($ic, $vc, $x, $f);
4829 pchip_chsp($ic, $vc, $x, $f, $d, $ierr); # all arguments given
4830 ($d, $ierr) = $ic->pchip_chsp($vc, $x, $f); # method call
4831 $ic->pchip_chsp($vc, $x, $f, $d, $ierr);
4832  
4833 =for ref
4834  
4835 Calculate the derivatives of (x,f(x)) using cubic spline interpolation.
4836  
4837 Computes the Hermite representation of the cubic spline interpolant
4838 to the data given in (C<$x,$f>), with the specified boundary conditions.
4839 Control over the boundary conditions is given by the
4840 C<$ic> and C<$vc> ndarrays.
4841 The resulting values - C<$x,$f,$d> - can
4842 be used in all the functions which expect a cubic
4843 Hermite function, including L</pchip_bvalu>.
4844  
4845 References: Carl de Boor, A Practical Guide to Splines, Springer-Verlag,
4846 New York, 1978, pp. 53-59.
4847  
4848 =pod
4849  
4850 =head3 Parameters
4851  
4852 =over
4853  
4854 =item ic
4855  
4856 The first and second elements determine the boundary
4857 conditions at the start and end of the data respectively.
4858 The allowed values for C<ic(0)> are:
4859  
4860 =over
4861  
4862 =item *
4863  
4864 0 to set C<d(0)> so that the third derivative is
4865 continuous at C<x(1)>.
4866  
4867 =item *
4868  
4869 1 if first derivative at C<x(0)> is given in C<vc(0>).
4870  
4871 =item *
4872  
4873 2 if second derivative at C<x(0>) is given in C<vc(0)>.
4874  
4875 =item *
4876  
4877 3 to use the 3-point difference formula for C<d(0)>.
4878 (Reverts to the default b.c. if C<n E<lt> 3>.)
4879  
4880 =item *
4881  
4882 4 to use the 4-point difference formula for C<d(0)>.
4883 (Reverts to the default b.c. if C<n E<lt> 4>.)
4884  
4885 =back
4886  
4887 The values for C<ic(1)> are the same as above, except that
4888 the first-derivative value is stored in C<vc(1)> for cases 1 and 2.
4889 The values of C<$vc> need only be set if options 1 or 2 are chosen
4890 for C<$ic>.
4891  
4892 NOTES: For the "natural" boundary condition, use IC(n)=2 and VC(n)=0.
4893  
4894 =item vc
4895  
4896 See ic for details
4897  
4898 =item ierr
4899  
4900 Error status:
4901  
4902 =over
4903  
4904 =item *
4905  
4906 0 if successful.
4907  
4908 =item *
4909  
4910 -1 if C<dim($x, 0) E<lt> 2>.
4911  
4912 =item *
4913  
4914 -3 if C<$x> is not strictly increasing.
4915  
4916 =item *
4917  
4918 -4 if C<ic(0) E<lt> 0> or C<ic(0) E<gt> 4>.
4919  
4920 =item *
4921  
4922 -5 if C<ic(1) E<lt> 0> or C<ic(1) E<gt> 4>.
4923  
4924 =item *
4925  
4926 -6 if both of the above are true.
4927  
4928 =item *
4929  
4930 -7 if C<nwk E<lt> 2*n>.
4931  
4932 NOTE: The above errors are checked in the order listed,
4933 and following arguments have B<NOT> been validated.
4934 (The D-array has not been changed in any of these cases.)
4935  
4936 =item *
4937  
4938 -8 in case of trouble solving the linear system
4939 for the interior derivative values.
4940 (The D-array may have been changed in this case. Do B<NOT> use it!)
4941  
4942 =back
4943  
4944 =back
4945  
4946 Broadcasts over its inputs.
4947  
4948 =for bad
4949  
4950 C<pchip_chsp> does not process bad values.
4951 It will set the bad-value flag of all output ndarrays if the flag is set for any of the input ndarrays.
4952  
4953 =cut
4954  
4955  
4956  
4957  
4958 *pchip_chsp = \&PDL::pchip_chsp;
4959  
4960  
4961  
4962  
4963  
4964  
4965 =head2 pchip_chfd
4966  
4967 =for sig
4968  
4969 Signature: (x(n); f(n); d(n); xe(ne);
4970 [o] fe(ne); [o] de(ne); indx [o] ierr(); int [o] skip())
4971 Types: (float double ldouble)
4972  
4973 =for usage
4974  
4975 ($fe, $de, $ierr, $skip) = pchip_chfd($x, $f, $d, $xe);
4976 pchip_chfd($x, $f, $d, $xe, $fe, $de, $ierr, $skip); # all arguments given
4977 ($fe, $de, $ierr, $skip) = $x->pchip_chfd($f, $d, $xe); # method call
4978 $x->pchip_chfd($f, $d, $xe, $fe, $de, $ierr, $skip);
4979  
4980 =for ref
4981  
4982 Evaluate a piecewise cubic Hermite function and its first derivative
4983 at an array of points. May be used by itself for Hermite interpolation,
4984 or as an evaluator for DPCHIM or DPCHIC.
4985  
4986 Given a piecewise cubic Hermite function - such as from
4987 L</pchip_chim> - evaluate the function (C<$fe>) and
4988 derivative (C<$de>) at a set of points (C<$xe>).
4989 If function values alone are required, use L</pchip_chfe>.
4990  
4991 =pod
4992  
4993 =head3 Parameters
4994  
4995 =over
4996  
4997 =item xe
4998  
4999 array of points at which the functions are to
5000 be evaluated. NOTES:
5001  
5002 =over
5003  
5004 =item 1
5005  
5006 The evaluation will be most efficient if the elements
5007 of XE are increasing relative to X;
5008 that is, XE(J) .GE. X(I)
5009 implies XE(K) .GE. X(I), all K.GE.J .
5010  
5011 =item 2
5012  
5013 If any of the XE are outside the interval [X(1),X(N)],
5014 values are extrapolated from the nearest extreme cubic,
5015 and a warning error is returned.
5016  
5017 =back
5018  
5019 =item fe
5020  
5021 array of values of the cubic Hermite
5022 function defined by N, X, F, D at the points XE.
5023  
5024 =item de
5025  
5026 array of values of the first derivative of the same function at the points XE.
5027  
5028 =item ierr
5029  
5030 Error status:
5031  
5032 =over
5033  
5034 =item *
5035  
5036 0 if successful.
5037  
5038 =item *
5039  
5040 E<gt>0 if extrapolation was performed at C<ierr> points
5041 (data still valid).
5042  
5043 =item *
5044  
5045 -1 if C<dim($x, 0) E<lt> 2>
5046  
5047 =item *
5048  
5049 -3 if C<$x> is not strictly increasing.
5050  
5051 =item *
5052  
5053 -4 if C<dim($xe, 0) E<lt> 1>.
5054  
5055 =item *
5056  
5057 -5 if an error has occurred in a lower-level routine,
5058 which should never happen.
5059  
5060 =back
5061  
5062 =item skip
5063  
5064 Set to 1 to skip checks on the input data.
5065 This will save time in case these checks have already
5066 been performed (say, in L</pchip_chim> or L</pchip_chic>).
5067 Will be set to TRUE on normal return.
5068  
5069 =back
5070  
5071 Broadcasts over its inputs.
5072  
5073 =for bad
5074  
5075 C<pchip_chfd> does not process bad values.
5076 It will set the bad-value flag of all output ndarrays if the flag is set for any of the input ndarrays.
5077  
5078 =cut
5079  
5080  
5081  
5082  
5083 *pchip_chfd = \&PDL::pchip_chfd;
5084  
5085  
5086  
5087  
5088  
5089  
5090 =head2 pchip_chfe
5091  
5092 =for sig
5093  
5094 Signature: (x(n); f(n); d(n); xe(ne);
5095 [o] fe(ne); indx [o] ierr(); int [o] skip())
5096 Types: (float double ldouble)
5097  
5098 =for usage
5099  
5100 ($fe, $ierr, $skip) = pchip_chfe($x, $f, $d, $xe);
5101 pchip_chfe($x, $f, $d, $xe, $fe, $ierr, $skip); # all arguments given
5102 ($fe, $ierr, $skip) = $x->pchip_chfe($f, $d, $xe); # method call
5103 $x->pchip_chfe($f, $d, $xe, $fe, $ierr, $skip);
5104  
5105 =for ref
5106  
5107 Evaluate a piecewise cubic Hermite function at an array of points.
5108 May be used by itself for Hermite interpolation, or as an evaluator
5109 for L</pchip_chim> or L</pchip_chic>.
5110  
5111 Given a piecewise cubic Hermite function - such as from
5112 L</pchip_chim> - evaluate the function (C<$fe>) at
5113 a set of points (C<$xe>).
5114 If derivative values are also required, use L</pchip_chfd>.
5115  
5116 =pod
5117  
5118 =head3 Parameters
5119  
5120 =over
5121  
5122 =item x
5123  
5124 array of independent variable values. The
5125 elements of X must be strictly increasing:
5126  
5127 X(I-1) .LT. X(I), I = 2(1)N.
5128  
5129 (Error return if not.)
5130  
5131 =item f
5132  
5133 array of function values. F(I) is the value corresponding to X(I).
5134  
5135 =item d
5136  
5137 array of derivative values. D(I) is the value corresponding to X(I).
5138  
5139 =item xe
5140  
5141 array of points at which the function is to be evaluated. NOTES:
5142  
5143 =over
5144  
5145 =item 1
5146  
5147 The evaluation will be most efficient if the elements
5148 of XE are increasing relative to X;
5149 that is, XE(J) .GE. X(I)
5150 implies XE(K) .GE. X(I), all K.GE.J .
5151  
5152 =item 2
5153  
5154 If any of the XE are outside the interval [X(1),X(N)],
5155 values are extrapolated from the nearest extreme cubic,
5156 and a warning error is returned.
5157  
5158 =back
5159  
5160 =item fe
5161  
5162 array of values of the cubic Hermite
5163 function defined by N, X, F, D at the points XE.
5164  
5165 =item ierr
5166  
5167 Error status returned by C<$>:
5168  
5169 =over
5170  
5171 =item *
5172  
5173 0 if successful.
5174  
5175 =item *
5176  
5177 E<gt>0 if extrapolation was performed at C<ierr> points
5178 (data still valid).
5179  
5180 =item *
5181  
5182 -1 if C<dim($x, 0) E<lt> 2>
5183  
5184 =item *
5185  
5186 -3 if C<$x> is not strictly increasing.
5187  
5188 =item *
5189  
5190 -4 if C<dim($xe, 0) E<lt> 1>.
5191  
5192 =back
5193  
5194 (The FE-array has not been changed in any of these cases.)
5195 NOTE: The above errors are checked in the order listed,
5196 and following arguments have B<NOT> been validated.
5197  
5198 =item skip
5199  
5200 Set to 1 to skip checks on the input data.
5201 This will save time in case these checks have already
5202 been performed (say, in L</pchip_chim> or L</pchip_chic>).
5203 Will be set to TRUE on normal return.
5204  
5205 =back
5206  
5207 Broadcasts over its inputs.
5208  
5209 =for bad
5210  
5211 C<pchip_chfe> does not process bad values.
5212 It will set the bad-value flag of all output ndarrays if the flag is set for any of the input ndarrays.
5213  
5214 =cut
5215  
5216  
5217  
5218  
5219 *pchip_chfe = \&PDL::pchip_chfe;
5220  
5221  
5222  
5223  
5224  
5225  
5226 =head2 pchip_chia
5227  
5228 =for sig
5229  
5230 Signature: (x(n); f(n); d(n); la(); lb();
5231 [o]ans(); indx [o]ierr(); int [o]skip())
5232 Types: (float double ldouble)
5233  
5234 =for usage
5235  
5236 ($ans, $ierr, $skip) = pchip_chia($x, $f, $d, $la, $lb);
5237 pchip_chia($x, $f, $d, $la, $lb, $ans, $ierr, $skip); # all arguments given
5238 ($ans, $ierr, $skip) = $x->pchip_chia($f, $d, $la, $lb); # method call
5239 $x->pchip_chia($f, $d, $la, $lb, $ans, $ierr, $skip);
5240  
5241 =for ref
5242  
5243 Integrate (x,f(x)) over arbitrary limits.
5244  
5245 Evaluate the definite integral of a piecewise
5246 cubic Hermite function over an arbitrary interval, given by C<[$la,$lb]>.
5247  
5248 =pod
5249  
5250 =head3 Parameters
5251  
5252 =over
5253  
5254 =item x
5255  
5256 array of independent variable values. The elements
5257 of X must be strictly increasing (error return if not):
5258  
5259 X(I-1) .LT. X(I), I = 2(1)N.
5260  
5261 =item f
5262  
5263 array of function values. F(I) is the value corresponding to X(I).
5264  
5265 =item d
5266  
5267 should contain the derivative values, computed by L</pchip_chim>.
5268 See L</pchip_chid> if the integration limits are data points.
5269  
5270 =item la
5271  
5272 The values of C<$la> and C<$lb> do not have
5273 to lie within C<$x>, although the resulting integral
5274 value will be highly suspect if they are not.
5275  
5276 =item lb
5277  
5278 See la
5279  
5280 =item ierr
5281  
5282 Error status:
5283  
5284 =over
5285  
5286 =item *
5287  
5288 0 if successful.
5289  
5290 =item *
5291  
5292 1 if C<$la> lies outside C<$x>.
5293  
5294 =item *
5295  
5296 2 if C<$lb> lies outside C<$x>.
5297  
5298 =item *
5299  
5300 3 if both 1 and 2 are true. (Note that this means that either [A,B]
5301 contains data interval or the intervals do not intersect at all.)
5302  
5303 =item *
5304  
5305 -1 if C<dim($x, 0) E<lt> 2>
5306  
5307 =item *
5308  
5309 -3 if C<$x> is not strictly increasing.
5310  
5311 =item *
5312  
5313 -4 if an error has occurred in a lower-level routine,
5314 which should never happen.
5315  
5316 =back
5317  
5318 =item skip
5319  
5320 Set to 1 to skip checks on the input data.
5321 This will save time in case these checks have already
5322 been performed (say, in L</pchip_chim> or L</pchip_chic>).
5323 Will be set to TRUE on return with IERR E<gt>= 0.
5324  
5325 =back
5326  
5327 Broadcasts over its inputs.
5328  
5329 =for bad
5330  
5331 C<pchip_chia> does not process bad values.
5332 It will set the bad-value flag of all output ndarrays if the flag is set for any of the input ndarrays.
5333  
5334 =cut
5335  
5336  
5337  
5338  
5339 *pchip_chia = \&PDL::pchip_chia;
5340  
5341  
5342  
5343  
5344  
5345  
5346 =head2 pchip_chid
5347  
5348 =for sig
5349  
5350 Signature: (x(n); f(n); d(n);
5351 indx ia(); indx ib();
5352 [o]ans(); indx [o]ierr(); int [o]skip())
5353 Types: (float double ldouble)
5354  
5355 =for usage
5356  
5357 ($ans, $ierr, $skip) = pchip_chid($x, $f, $d, $ia, $ib);
5358 pchip_chid($x, $f, $d, $ia, $ib, $ans, $ierr, $skip); # all arguments given
5359 ($ans, $ierr, $skip) = $x->pchip_chid($f, $d, $ia, $ib); # method call
5360 $x->pchip_chid($f, $d, $ia, $ib, $ans, $ierr, $skip);
5361  
5362 =for ref
5363  
5364 Evaluate the definite integral of a piecewise cubic Hermite function
5365 over an interval whose endpoints are data points.
5366  
5367 Evaluate the definite integral of a a piecewise cubic Hermite
5368 function between C<x($ia)> and C<x($ib)>.
5369  
5370 See L</pchip_chia> for integration between arbitrary
5371 limits.
5372  
5373 =pod
5374  
5375 =head3 Parameters
5376  
5377 =over
5378  
5379 =item x
5380  
5381 array of independent variable values. The
5382 elements of X must be strictly increasing:
5383  
5384 X(I-1) .LT. X(I), I = 2(1)N.
5385  
5386 (Error return if not.)
5387  
5388 It is a fatal error to pass in data with C<N> E<lt> 2.
5389  
5390 =item f
5391  
5392 array of function values. F(I) is the value corresponding to X(I).
5393  
5394 =item d
5395  
5396 should contain the derivative values, computed by L</pchip_chim>.
5397  
5398 =item ia
5399  
5400 IA,IB -- (input) indices in X-array for the limits of integration.
5401 both must be in the range [0,N-1] (this is different from the Fortran
5402 version) - error return if not. No restrictions on their relative
5403 values.
5404  
5405 =item ib
5406  
5407 See ia for details
5408  
5409 =item ierr
5410  
5411 Error status - this will be set, but an exception
5412 will also be thrown:
5413  
5414 =over
5415  
5416 =item *
5417  
5418 0 if successful.
5419  
5420 =item *
5421  
5422 -3 if C<$x> is not strictly increasing.
5423  
5424 =item *
5425  
5426 -4 if C<$ia> or C<$ib> is out of range.
5427  
5428 =back
5429  
5430 (VALUE will be zero in any of these cases.)
5431 NOTE: The above errors are checked in the order listed, and following
5432 arguments have B<NOT> been validated.
5433  
5434 =item skip
5435  
5436 Set to 1 to skip checks on the input data.
5437 This will save time in case these checks have already
5438 been performed (say, in L</pchip_chim> or L</pchip_chic>).
5439 Will be set to TRUE on return with IERR of 0 or -4.
5440  
5441 =back
5442  
5443 Broadcasts over its inputs.
5444  
5445 =for bad
5446  
5447 C<pchip_chid> does not process bad values.
5448 It will set the bad-value flag of all output ndarrays if the flag is set for any of the input ndarrays.
5449  
5450 =cut
5451  
5452  
5453  
5454  
5455 *pchip_chid = \&PDL::pchip_chid;
5456  
5457  
5458  
5459  
5460  
5461  
5462 =head2 pchip_chbs
5463  
5464 =for sig
5465  
5466 Signature: (x(n); f(n); d(n); sbyte knotyp();
5467 [o]t(nknots=CALC(2*$SIZE(n)+4));
5468 [o]bcoef(ndim=CALC(2*$SIZE(n))); indx [o]ierr())
5469 Types: (float double ldouble)
5470  
5471 =for usage
5472  
5473 ($t, $bcoef, $ierr) = pchip_chbs($x, $f, $d, $knotyp);
5474 pchip_chbs($x, $f, $d, $knotyp, $t, $bcoef, $ierr); # all arguments given
5475 ($t, $bcoef, $ierr) = $x->pchip_chbs($f, $d, $knotyp); # method call
5476 $x->pchip_chbs($f, $d, $knotyp, $t, $bcoef, $ierr);
5477  
5478 =for ref
5479  
5480 Piecewise Cubic Hermite function to B-Spline converter.
5481  
5482 Computes the B-spline representation of the PCH function
5483 determined by N,X,F,D. The output is the B-representation for the
5484 function: NKNOTS, T, BCOEF, NDIM, KORD.
5485  
5486 L</pchip_chic>, L</pchip_chim>, or L</pchip_chsp> can be used to
5487 determine an interpolating PCH function from a set of data. The
5488 B-spline routine L</pchip_bvalu> can be used to evaluate the
5489 resulting B-spline representation of the data
5490 (i.e. C<nknots>, C<t>, C<bcoeff>, C<ndim>, and
5491 C<kord>).
5492  
5493 Caution: Since it is assumed that the input PCH function has been
5494 computed by one of the other routines in the package PCHIP,
5495 input arguments N, X are B<not> checked for validity.
5496  
5497 Restrictions/assumptions:
5498  
5499 =over
5500  
5501 =item C<1>
5502  
5503 N.GE.2 . (not checked)
5504  
5505 =item C<2>
5506  
5507 X(i).LT.X(i+1), i=1,...,N . (not checked)
5508  
5509 =item C<4>
5510  
5511 KNOTYP.LE.2 . (error return if not)
5512  
5513 =item C<6>
5514  
5515 T(2*k+1) = T(2*k) = X(k), k=1,...,N . (not checked)
5516  
5517 * Indicates this applies only if KNOTYP.LT.0 .
5518  
5519 =back
5520  
5521 References: F. N. Fritsch, "Representations for parametric cubic
5522 splines," Computer Aided Geometric Design 6 (1989), pp.79-82.
5523  
5524 =pod
5525  
5526 =head3 Parameters
5527  
5528 =over
5529  
5530 =item f
5531  
5532 the array of dependent variable values.
5533 C<f(I)> is the value corresponding to C<x(I)>.
5534  
5535 =item d
5536  
5537 the array of derivative values at the data points.
5538 C<d(I)> is the value corresponding to C<x(I)>.
5539  
5540 =item knotyp
5541  
5542 flag which controls the knot sequence.
5543 The knot sequence C<t> is normally computed from C<$x>
5544 by putting a double knot at each C<x> and setting the end knot pairs
5545 according to the value of C<knotyp> (where C<m = ndim = 2*n>):
5546  
5547 =over
5548  
5549 =item *
5550  
5551 0 - Quadruple knots at the first and last points.
5552  
5553 =item *
5554  
5555 1 - Replicate lengths of extreme subintervals:
5556 C<t( 0 ) = t( 1 ) = x(0) - (x(1)-x(0))> and
5557 C<t(m+3) = t(m+2) = x(n-1) + (x(n-1)-x(n-2))>
5558  
5559 =item *
5560  
5561 2 - Periodic placement of boundary knots:
5562 C<t( 0 ) = t( 1 ) = x(0) - (x(n-1)-x(n-2))> and
5563 C<t(m+3) = t(m+2) = x(n) + (x(1)-x(0))>
5564  
5565 =item *
5566  
5567 E<lt>0 - Assume the C<nknots> and C<t> were set in a previous call.
5568 This option is provided for improved efficiency when used
5569 in a parametric setting.
5570  
5571 =back
5572  
5573 =item t
5574  
5575 the array of C<2*n+4> knots for the B-representation
5576 and may be changed by the routine.
5577 If C<knotyp E<gt>= 0>, C<t> will be changed so that the
5578 interior double knots are equal to the x-values and the
5579 boundary knots set as indicated above,
5580 otherwise it is assumed that C<t> was set by a
5581 previous call (no check is made to verify that the data
5582 forms a legitimate knot sequence).
5583  
5584 =item bcoef
5585  
5586 the array of 2*N B-spline coefficients.
5587  
5588 =item ierr
5589  
5590 Error status:
5591  
5592 =over
5593  
5594 =item *
5595  
5596 0 if successful.
5597  
5598 =item *
5599  
5600 -4 if C<knotyp E<gt> 2>. (recoverable)
5601  
5602 =item *
5603  
5604 -5 if C<knotyp E<lt> 0> and C<nknots != 2*n + 4>. (recoverable)
5605  
5606 =back
5607  
5608 =back
5609  
5610 Broadcasts over its inputs.
5611  
5612 =for bad
5613  
5614 C<pchip_chbs> does not process bad values.
5615 It will set the bad-value flag of all output ndarrays if the flag is set for any of the input ndarrays.
5616  
5617 =cut
5618  
5619  
5620  
5621  
5622 *pchip_chbs = \&PDL::pchip_chbs;
5623  
5624  
5625  
5626  
5627  
5628  
5629 =head2 pchip_bvalu
5630  
5631 =for sig
5632  
5633 Signature: (t(nplusk); a(n); indx ideriv(); x();
5634 [o]ans(); indx [o] inbv();
5635 [t] work(k3=CALC(3*($SIZE(nplusk)-$SIZE(n))));)
5636 Types: (float double ldouble)
5637  
5638 =for usage
5639  
5640 ($ans, $inbv) = pchip_bvalu($t, $a, $ideriv, $x);
5641 pchip_bvalu($t, $a, $ideriv, $x, $ans, $inbv); # all arguments given
5642 ($ans, $inbv) = $t->pchip_bvalu($a, $ideriv, $x); # method call
5643 $t->pchip_bvalu($a, $ideriv, $x, $ans, $inbv);
5644  
5645 =for ref
5646  
5647 Evaluate the B-representation of a B-spline at X for the
5648 function value or any of its derivatives.
5649  
5650 Evaluates the B-representation C<(T,A,N,K)> of a B-spline
5651 at C<X> for the function value on C<IDERIV = 0> or any of its
5652 derivatives on C<IDERIV = 1,2,...,K-1>. Right limiting values
5653 (right derivatives) are returned except at the right end
5654 point C<X=T(N+1)> where left limiting values are computed. The
5655 spline is defined on C<T(K) .LE. X .LE. T(N+1)>. BVALU returns
5656 a fatal error message when C<X> is outside of this interval.
5657  
5658 To compute left derivatives or left limiting values at a
5659 knot C<T(I)>, replace C<N> by C<I-1> and set C<X=T(I)>, C<I=K+1,N+1>.
5660  
5661 References: Carl de Boor, Package for calculating with B-splines,
5662 SIAM Journal on Numerical Analysis 14, 3 (June 1977), pp. 441-472.
5663  
5664 =pod
5665  
5666 =head3 Parameters
5667  
5668 =over
5669  
5670 =item t
5671  
5672 knot vector of length N+K
5673  
5674 =item a
5675  
5676 B-spline coefficient vector of length N,
5677 the number of B-spline coefficients; N = sum of knot multiplicities-K
5678  
5679 =item ideriv
5680  
5681 order of the derivative, 0 .LE. IDERIV .LE. K-1
5682  
5683 IDERIV=0 returns the B-spline value
5684  
5685 =item x
5686  
5687 T(K) .LE. X .LE. T(N+1)
5688  
5689 =item ans
5690  
5691 value of the IDERIV-th derivative at X
5692  
5693 =item inbv
5694  
5695 contains information for efficient processing after the initial
5696 call and INBV must not
5697 be changed by the user. Distinct splines require distinct INBV parameters.
5698  
5699 =back
5700  
5701 Broadcasts over its inputs.
5702  
5703 =for bad
5704  
5705 C<pchip_bvalu> does not process bad values.
5706 It will set the bad-value flag of all output ndarrays if the flag is set for any of the input ndarrays.
5707  
5708 =cut
5709  
5710  
5711  
5712  
5713 *pchip_bvalu = \&PDL::pchip_bvalu;
5714  
5715  
5716  
5717  
5718  
5719  
5720  
5721 #line 6287 "lib/PDL/Primitive.pd"
5722  
5723 =head1 AUTHOR
5724  
5725 Copyright (C) Tuomas J. Lukka 1997 (lukka@husc.harvard.edu). Contributions
5726 by Christian Soeller (c.soeller@auckland.ac.nz), Karl Glazebrook
5727 (kgb@aaoepp.aao.gov.au), Craig DeForest (deforest@boulder.swri.edu)
5728 and Jarle Brinchmann (jarle@astro.up.pt)
5729 All rights reserved. There is no warranty. You are allowed
5730 to redistribute this software / documentation under certain
5731 conditions. For details, see the file COPYING in the PDL
5732 distribution. If this file is separated from the PDL distribution,
5733 the copyright notice should be included in the file.
5734  
5735 Updated for CPAN viewing compatibility by David Mertens.
5736  
5737 =cut
5738 #line 5739 "lib/PDL/Primitive.pm"
5739  
5740 # Exit with OK status
5741  
5742 1;
« lib/PDL/PP.pm ↑ Summary lib/PDL/Slices.pm »