-
Notifications
You must be signed in to change notification settings - Fork 44
/
primitive.pd
4084 lines (3266 loc) · 109 KB
/
primitive.pd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use strict;
use warnings;
use PDL::Types qw(ppdefs_all types);
my $F = [map $_->ppsym, grep $_->real && !$_->integer, types()];
my $AF = [map $_->ppsym, grep !$_->integer, types];
pp_addpm({At=>'Top'},<<'EOD');
use strict;
use warnings;
use PDL::Slices;
use Carp;
{ package PDL;
use overload (
'x' => sub {
PDL::Primitive::matmult(@_[0,1], my $foo=$_[0]->null());
$foo;
},
);
}
=head1 NAME
PDL::Primitive - primitive operations for pdl
=head1 DESCRIPTION
This module provides some primitive and useful functions defined
using PDL::PP and able to use the new indexing tricks.
See L<PDL::Indexing> for how to use indices creatively.
For explanation of the signature format, see L<PDL::PP>.
=head1 SYNOPSIS
# Pulls in PDL::Primitive, among other modules.
use PDL;
# Only pull in PDL::Primitive:
use PDL::Primitive;
=cut
EOD
################################################################
# a whole bunch of quite basic functions for inner, outer
# and matrix products (operations that are not normally
# available via operator overloading)
################################################################
pp_def(
'inner',
HandleBad => 1,
Pars => 'a(n); b(n); [o]c();',
GenericTypes => [ppdefs_all],
Code =>
'double tmp = 0;
int badflag = 0;
loop(n) %{
PDL_IF_BAD(if (!($ISGOOD(a()) && $ISGOOD(b()))) { badflag = 1; break; }
else,) { tmp += $a() * $b(); }
%}
PDL_IF_BAD(if (badflag) { $SETBAD(c()); $PDLSTATESETBAD(c); }
else,) { $c() = tmp; }',
Doc => '
=for ref
Inner product over one dimension
c = sum_i a_i * b_i
',
BadDoc => '
=for bad
If C<a() * b()> contains only bad data,
C<c()> is set bad. Otherwise C<c()> will have its bad flag cleared,
as it will not contain any bad values.
',
); # pp_def( inner )
pp_def(
'outer',
HandleBad => 1,
Pars => 'a(n); b(m); [o]c(n,m);',
GenericTypes => [ppdefs_all],
Code =>
'loop(n,m) %{
PDL_IF_BAD(if ( $ISBAD(a()) || $ISBAD(b()) ) {
$SETBAD(c());
} else,) {
$c() = $a() * $b();
}
%}',
Doc => '
=for ref
outer product over one dimension
Naturally, it is possible to achieve the effects of outer
product simply by broadcasting over the "C<*>"
operator but this function is provided for convenience.
'); # pp_def( outer )
pp_addpm(<<'EOD');
=head2 x
=for sig
Signature: (a(i,z), b(x,i),[o]c(x,z))
=for ref
Matrix multiplication
PDL overloads the C<x> operator (normally the repeat operator) for
matrix multiplication. The number of columns (size of the 0
dimension) in the left-hand argument must normally equal the number of
rows (size of the 1 dimension) in the right-hand argument.
Row vectors are represented as (N x 1) two-dimensional PDLs, or you
may be sloppy and use a one-dimensional PDL. Column vectors are
represented as (1 x N) two-dimensional PDLs.
Broadcasting occurs in the usual way, but as both the 0 and 1 dimension
(if present) are included in the operation, you must be sure that
you don't try to broadcast over either of those dims.
Of note, due to how Perl v5.14.0 and above implement operator overloading of
the C<x> operator, the use of parentheses for the left operand creates a list
context, that is
pdl> ( $x * $y ) x $z
ERROR: Argument "..." isn't numeric in repeat (x) ...
treats C<$z> as a numeric count for the list repeat operation and does not call
the scalar form of the overloaded operator. To use the operator in this case,
use a scalar context:
pdl> scalar( $x * $y ) x $z
or by calling L</matmult> directly:
pdl> ( $x * $y )->matmult( $z )
EXAMPLES
Here are some simple ways to define vectors and matrices:
pdl> $r = pdl(1,2); # A row vector
pdl> $c = pdl([[3],[4]]); # A column vector
pdl> $c = pdl(3,4)->(*1); # A column vector, using NiceSlice
pdl> $m = pdl([[1,2],[3,4]]); # A 2x2 matrix
Now that we have a few objects prepared, here is how to
matrix-multiply them:
pdl> print $r x $m # row x matrix = row
[
[ 7 10]
]
pdl> print $m x $r # matrix x row = ERROR
PDL: Dim mismatch in matmult of [2x2] x [2x1]: 2 != 1
pdl> print $m x $c # matrix x column = column
[
[ 5]
[11]
]
pdl> print $m x 2 # Trivial case: scalar mult.
[
[2 4]
[6 8]
]
pdl> print $r x $c # row x column = scalar
[
[11]
]
pdl> print $c x $r # column x row = matrix
[
[3 6]
[4 8]
]
INTERNALS
The mechanics of the multiplication are carried out by the
L</matmult> method.
=cut
EOD
pp_def('matmult',
HandleBad=>0,
Pars => 'a(t,h); b(w,t); [o]c(w,h);',
GenericTypes => [ppdefs_all],
PMCode => pp_line_numbers(__LINE__, <<'EOPM'),
sub PDL::matmult {
my ($x,$y,$c) = @_;
$y = PDL->topdl($y);
$c = PDL->null unless do { local $@; eval { $c->isa('PDL') } };
while($x->getndims < 2) {$x = $x->dummy(-1)}
while($y->getndims < 2) {$y = $y->dummy(-1)}
return ($c .= $x * $y) if( ($x->dim(0)==1 && $x->dim(1)==1) ||
($y->dim(0)==1 && $y->dim(1)==1) );
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)
if $y->dim(1) != $x->dim(0);
PDL::_matmult_int($x,$y,$c);
$c;
}
EOPM
Code => <<'EOC',
PDL_Indx ih, iw, it, ow, oh, ot, wlim, hlim, tlim;
PDL_Indx tsiz = 8 * sizeof(double) / sizeof($GENERIC());
// Cache the dimincs to avoid constant lookups
PDL_Indx atdi = PDL_REPRINCS($PDL(a))[0];
PDL_Indx btdi = PDL_REPRINCS($PDL(b))[1];
// Loop over tiles
for( oh=0; oh < $SIZE(h); oh += tsiz ) {
hlim = PDLMIN(oh + tsiz, $SIZE(h));
for( ow=0; ow < $SIZE(w); ow += tsiz ) {
wlim = PDLMIN(ow + tsiz, $SIZE(w));
// Zero the output for this tile
for( ih=oh; ih<hlim; ih++ )
for( iw=ow; iw<wlim; iw++ )
$c(w=>iw, h=>ih) = 0;
for( ot=0; ot < $SIZE(t); ot += tsiz ) {
tlim = PDLMIN(ot + tsiz, $SIZE(t));
for( ih=oh; ih<hlim; ih++ ) {
for( iw=ow; iw<wlim; iw++ ) {
// Cache the accumulated value for the output
$GENERIC() cc = $c(w=>iw, h=>ih);
// Cache data pointers before 't' run through tile
$GENERIC() *ad = &($a(t=>ot, h=>ih));
$GENERIC() *bd = &($b(w=>iw, t=>ot));
// Hotspot - run the 't' summation
for( it=ot; it<tlim; it++ ) {
cc += *ad * *bd;
ad += atdi;
bd += btdi;
}
// put the output back to be further accumulated later
$c(w=>iw, h=>ih) = cc;
}
}
}
}
}
EOC
Doc => <<'EOD'
=for ref
Matrix multiplication
Notionally, matrix multiplication $x x $y is equivalent to the
broadcasting expression
$x->dummy(1)->inner($y->xchg(0,1)->dummy(2),$c);
but for large matrices that breaks CPU cache and is slow. Instead,
matmult calculates its result in 32x32x32 tiles, to keep the memory
footprint within cache as long as possible on most modern CPUs.
For usage, see L</x>, a description of the overloaded 'x' operator
EOD
);
pp_def(
'innerwt',
HandleBad => 1,
Pars => 'a(n); b(n); c(n); [o]d();',
GenericTypes => [ppdefs_all],
Code =>
'long double tmp = 0;
int flag = 0;
loop(n) %{
PDL_IF_BAD(if ( $ISGOOD(a()) && $ISGOOD(b()) && $ISGOOD(c()) ),) {
tmp += $a() * $b() * $c();
flag = 1;
}
%}
PDL_IF_BAD(if (!flag) { $SETBAD(d()); }
else,) { $d() = tmp; }',
Doc => '
=for ref
Weighted (i.e. triple) inner product
d = sum_i a(i) b(i) c(i)
=cut
'
);
pp_def(
'inner2',
HandleBad => 1,
Pars => 'a(n); b(n,m); c(m); [o]d();',
GenericTypes => [ppdefs_all],
Code =>
'long double tmp = 0;
int flag = 0;
loop(n,m) %{
PDL_IF_BAD(if ( $ISGOOD(a()) && $ISGOOD(b()) && $ISGOOD(c()) ),) {
tmp += $a() * $b() * $c();
flag = 1;
}
%}
PDL_IF_BAD(if (!flag) { $SETBAD(d()); }
else,) { $d() = tmp; }',
Doc => '
=for ref
Inner product of two vectors and a matrix
d = sum_ij a(i) b(i,j) c(j)
Note that you should probably not broadcast over C<a> and C<c> since that would be
very wasteful. Instead, you should use a temporary for C<b*c>.
'
);
pp_def(
'inner2d',
HandleBad => 1,
Pars => 'a(n,m); b(n,m); [o]c();',
GenericTypes => [ppdefs_all],
Code =>
'long double tmp = 0;
int flag = 0;
loop(n,m) %{
PDL_IF_BAD(if ( $ISGOOD(a()) && $ISGOOD(b()) ),) {
tmp += $a() * $b();
flag = 1;
}
%}
PDL_IF_BAD(if (!flag) { $SETBAD(c()); }
else,) { $c() = tmp; }',
Doc => '
=for ref
Inner product over 2 dimensions.
Equivalent to
$c = inner($x->clump(2), $y->clump(2))
=cut
'
);
pp_def(
'inner2t',
HandleBad => 1,
Pars => 'a(j,n); b(n,m); c(m,k); [t]tmp(n,k); [o]d(j,k));',
GenericTypes => [ppdefs_all],
Code =>
'loop(n,k) %{
long double tmp0 = 0;
int flag = 0;
loop(m) %{
PDL_IF_BAD(if ( $ISGOOD(b()) && $ISGOOD(c()) ),) {
tmp0 += $b() * $c();
flag = 1;
}
%}
PDL_IF_BAD(if (!flag) { $SETBAD(tmp()); }
else,) { $tmp() = tmp0; }
%}
loop(j,k) %{
long double tmp1 = 0;
int flag = 0;
loop(n) %{
if ( $ISGOOD(a()) && $ISGOOD(tmp()) ) {
tmp1 += $a() * $tmp();
flag = 1;
}
%}
PDL_IF_BAD(if (!flag) { $SETBAD(d()); }
else,) { $d() = tmp1; }
%}',
Doc => '
=for ref
Efficient Triple matrix product C<a*b*c>
Efficiency comes from by using the temporary C<tmp>. This operation only
scales as C<N**3> whereas broadcasting using L</inner2> would scale
as C<N**4>.
The reason for having this routine is that you do not need to
have the same broadcast-dimensions for C<tmp> as for the other arguments,
which in case of large numbers of matrices makes this much more
memory-efficient.
It is hoped that things like this could be taken care of as a kind of
closures at some point.
=cut
'
); # pp_def inner2t()
# a helper function for the cross product definition
sub crassgn {
"\$c(tri => $_[0]) = \$a(tri => $_[1])*\$b(tri => $_[2]) -
\$a(tri => $_[2])*\$b(tri => $_[1]);"
}
pp_def('crossp',
Doc => <<'EOD',
=for ref
Cross product of two 3D vectors
After
=for example
$c = crossp $x, $y
the inner product C<$c*$x> and C<$c*$y> will be zero, i.e. C<$c> is
orthogonal to C<$x> and C<$y>
=cut
EOD
Pars => 'a(tri=3); b(tri); [o] c(tri)',
GenericTypes => [ppdefs_all],
Code =>
crassgn(0,1,2)."\n".
crassgn(1,2,0)."\n".
crassgn(2,0,1),
);
pp_def('norm',
HandleBad => 1,
Pars => 'vec(n); [o] norm(n)',
GenericTypes => [ppdefs_all],
Doc => 'Normalises a vector to unit Euclidean length',
Code =>
'long double sum=0;
int flag = 0;
loop(n) %{
PDL_IF_BAD(if ( $ISGOOD(vec()) ),) {
sum +=
PDL_IF_GENTYPE_REAL(
$vec()*$vec(),
creall($vec())*creall($vec()) + cimagl($vec())*cimagl($vec())
);
PDL_IF_BAD(flag = 1;,) }
%}
PDL_IF_BAD(if ( flag ),) {
if (sum > 0) {
sum = sqrt(sum);
loop(n) %{
PDL_IF_BAD(if ( $ISBAD(vec()) ) { $SETBAD(norm()); }
else ,) {
$norm() = $vec()/sum;
}
%}
} else {
loop(n) %{
if ( $ISBAD(vec()) ) { $SETBAD(norm()); }
else { $norm() = $vec(); }
%}
}
} PDL_IF_BAD(else {
loop(n) %{
$SETBAD(norm());
%}
},)
',
);
# this one was motivated by the need to compute
# the circular mean efficiently
# without it could not be done efficiently or without
# creating large intermediates (check pdl-porters for
# discussion)
# see PDL::ImageND for info about the circ_mean function
pp_def(
'indadd',
HandleBad => 1,
Pars => 'input(n); indx ind(n); [io] sum(m)',
GenericTypes => [ppdefs_all],
Code =>
'loop(n) %{
register PDL_Indx this_ind = $ind();
if ( PDL_IF_BAD($ISBADVAR(this_ind,ind) ||,) this_ind<0 || this_ind>=$SIZE(m) )
$CROAK("invalid index");
PDL_IF_BAD(
if ( $ISBAD(input()) ) { $SETBAD(sum(m => this_ind)); }
else,) { $sum(m => this_ind) += $input(); }
%}',
BadDoc => '
=for bad
The routine barfs on bad indices, and bad inputs set target outputs bad.
=cut
',
Doc=>'
=for ref
Broadcasting index add: add C<input> to the C<ind> element of C<sum>, i.e:
sum(ind) += input
=for example
Simple example:
$x = 2;
$ind = 3;
$sum = zeroes(10);
indadd($x,$ind, $sum);
print $sum
#Result: ( 2 added to element 3 of $sum)
# [0 0 0 2 0 0 0 0 0 0]
Broadcasting example:
$x = pdl( 1,2,3);
$ind = pdl( 1,4,6);
$sum = zeroes(10);
indadd($x,$ind, $sum);
print $sum."\n";
#Result: ( 1, 2, and 3 added to elements 1,4,6 $sum)
# [0 1 0 0 2 0 3 0 0 0]
=cut
');
# 1D convolution
# useful for broadcasted 1D filters
pp_addhdr('
/* Fast Modulus with proper negative behaviour */
#define REALMOD(a,b) while ((a)>=(b)) (a) -= (b); while ((a)<0) (a) += (b);
');
pp_def('conv1d',
Doc => << 'EOD',
=for ref
1D convolution along first dimension
The m-th element of the discrete convolution of an input ndarray
C<$a> of size C<$M>, and a kernel ndarray C<$kern> of size C<$P>, is
calculated as
n = ($P-1)/2
====
\
($a conv1d $kern)[m] = > $a_ext[m - n] * $kern[n]
/
====
n = -($P-1)/2
where C<$a_ext> is either the periodic (or reflected) extension of
C<$a> so it is equal to C<$a> on C< 0..$M-1 > and equal to the
corresponding periodic/reflected image of C<$a> outside that range.
=for example
$con = conv1d sequence(10), pdl(-1,0,1);
$con = conv1d sequence(10), pdl(-1,0,1), {Boundary => 'reflect'};
By default, periodic boundary conditions are assumed (i.e. wrap around).
Alternatively, you can request reflective boundary conditions using
the C<Boundary> option:
{Boundary => 'reflect'} # case in 'reflect' doesn't matter
The convolution is performed along the first dimension. To apply it across
another dimension use the slicing routines, e.g.
$y = $x->mv(2,0)->conv1d($kernel)->mv(0,2); # along third dim
This function is useful for broadcasted filtering of 1D signals.
Compare also L<conv2d|PDL::Image2D/conv2d>, L<convolve|PDL::ImageND/convolve>,
L<fftconvolve|PDL::FFT/fftconvolve()>, L<fftwconv|PDL::FFTW/fftwconv>,
L<rfftwconv|PDL::FFTW/rfftwconv>
=for bad
WARNING: C<conv1d> processes bad values in its inputs as
the numeric value of C<< $pdl->badvalue >> so it is not
recommended for processing pdls with bad values in them
unless special care is taken.
=cut
EOD
Pars => 'a(m); kern(p); [o]b(m);',
GenericTypes => [ppdefs_all],
OtherPars => 'int reflect;',
HandleBad => 0,
PMCode => pp_line_numbers(__LINE__, <<'EOPM'),
sub PDL::conv1d {
my $opt = pop @_ if ref($_[-1]) eq 'HASH';
die 'Usage: conv1d( a(m), kern(p), [o]b(m), {Options} )'
if @_<2 || @_>3;
my($x,$kern) = @_;
my $c = @_ == 3 ? $_[2] : PDL->null;
PDL::_conv1d_int($x,$kern,$c,
!(defined $opt && exists $$opt{Boundary}) ? 0 :
lc $$opt{Boundary} eq "reflect");
return $c;
}
EOPM
Code => '
int i,i1,i2,poff,pflip;
double tmp;
int reflect = $COMP(reflect);
int m_size = $SIZE(m);
int p_size = $SIZE(p);
poff = (p_size-1)/2;
for(i=0; i<m_size; i++) {
tmp = 0;
for(i1=0; i1<p_size; i1++) {
pflip = p_size - 1 - i1;
i2 = i+i1 - poff;
if (reflect && i2<0)
i2 = -i2;
if (reflect && i2>=m_size)
i2 = m_size-(i2-m_size+1);
REALMOD(i2,m_size);
tmp += $a(m=>i2) * $kern(p=>pflip);
}
$b(m=>i) = tmp;
}
');
# this can be achieved by
# ($x->dummy(0) == $y)->orover
# but this one avoids a larger intermediate and potentially shortcuts
pp_def('in',
Pars => 'a(); b(n); [o] c()',
GenericTypes => [ppdefs_all],
Code => '$c() = 0;
loop(n) %{ if ($a() == $b()) {$c() = 1; break;} %}',
Doc => <<'EOD',
=for ref
test if a is in the set of values b
=for example
$goodmsk = $labels->in($goodlabels);
print pdl(3,1,4,6,2)->in(pdl(2,3,3));
[1 0 0 0 1]
C<in> is akin to the I<is an element of> of set theory. In principle,
PDL broadcasting could be used to achieve its functionality by using a
construct like
$msk = ($labels->dummy(0) == $goodlabels)->orover;
However, C<in> doesn't create a (potentially large) intermediate
and is generally faster.
=cut
EOD
);
pp_add_exported ('', 'uniq');
pp_addpm (<< 'EOPM');
=head2 uniq
=for ref
return all unique elements of an ndarray
The unique elements are returned in ascending order.
=for example
PDL> p pdl(2,2,2,4,0,-1,6,6)->uniq
[-1 0 2 4 6] # 0 is returned 2nd (sorted order)
PDL> p pdl(2,2,2,4,nan,-1,6,6)->uniq
[-1 2 4 6 nan] # NaN value is returned at end
Note: The returned pdl is 1D; any structure of the input
ndarray is lost. C<NaN> values are never compare equal to
any other values, even themselves. As a result, they are
always unique. C<uniq> returns the NaN values at the end
of the result ndarray. This follows the Matlab usage.
See L</uniqind> if you need the indices of the unique
elements rather than the values.
=for bad
Bad values are not considered unique by uniq and are ignored.
$x=sequence(10);
$x=$x->setbadif($x%3);
print $x->uniq;
[0 3 6 9]
=cut
*uniq = \&PDL::uniq;
# return unique elements of array
# find as jumps in the sorted array
# flattens in the process
sub PDL::uniq {
my ($arr) = @_;
return $arr if($arr->nelem == 0); # The null list is unique (CED)
return $arr->flat if($arr->nelem == 1); # singleton list is unique
my $aflat = $arr->flat;
my $srt = $aflat->where($aflat==$aflat)->qsort; # no NaNs or BADs for qsort
my $nans = $aflat->where($aflat!=$aflat);
my $uniq = ($srt->nelem > 1) ? $srt->where($srt != $srt->rotate(-1)) : $srt;
# make sure we return something if there is only one value
(
$uniq->nelem > 0 ? $uniq :
$srt->nelem == 0 ? $srt :
PDL::pdl( ref($srt), [$srt->index(0)] )
)->append($nans);
}
EOPM
pp_add_exported ('', 'uniqind');
pp_addpm (<< 'EOPM');
=head2 uniqind
=for ref
Return the indices of all unique elements of an ndarray
The order is in the order of the values to be consistent
with uniq. C<NaN> values never compare equal with any
other value and so are always unique. This follows the
Matlab usage.
=for example
PDL> p pdl(2,2,2,4,0,-1,6,6)->uniqind
[5 4 1 3 6] # the 0 at index 4 is returned 2nd, but...
PDL> p pdl(2,2,2,4,nan,-1,6,6)->uniqind
[5 1 3 6 4] # ...the NaN at index 4 is returned at end
Note: The returned pdl is 1D; any structure of the input
ndarray is lost.
See L</uniq> if you want the unique values instead of the
indices.
=for bad
Bad values are not considered unique by uniqind and are ignored.
=cut
*uniqind = \&PDL::uniqind;
# return unique elements of array
# find as jumps in the sorted array
# flattens in the process
sub PDL::uniqind {
use PDL::Core 'barf';
my ($arr) = @_;
return $arr if($arr->nelem == 0); # The null list is unique (CED)
# Different from uniq we sort and store the result in an intermediary
my $aflat = $arr->flat;
my $nanind = which($aflat!=$aflat); # NaN indexes
my $good = PDL->sequence(indx, $aflat->dims)->where($aflat==$aflat); # good indexes
my $i_srt = $aflat->where($aflat==$aflat)->qsorti; # no BAD or NaN values for qsorti
my $srt = $aflat->where($aflat==$aflat)->index($i_srt);
my $uniqind;
if ($srt->nelem > 0) {
$uniqind = which($srt != $srt->rotate(-1));
$uniqind = $i_srt->slice('0') if $uniqind->isempty;
} else {
$uniqind = which($srt);
}
# Now map back to the original space
my $ansind = $nanind;
if ( $uniqind->nelem > 0 ) {
$ansind = ($good->index($i_srt->index($uniqind)))->append($ansind);
} else {
$ansind = $uniqind->append($ansind);
}
return $ansind;
}
EOPM
pp_add_exported ('', 'uniqvec');
pp_addpm (<< 'EOPM');
=head2 uniqvec
=for ref
Return all unique vectors out of a collection
NOTE: If any vectors in the input ndarray have NaN values
they are returned at the end of the non-NaN ones. This is
because, by definition, NaN values never compare equal with
any other value.
NOTE: The current implementation does not sort the vectors
containing NaN values.
The unique vectors are returned in lexicographically sorted
ascending order. The 0th dimension of the input PDL is treated
as a dimensional index within each vector, and the 1st and any
higher dimensions are taken to run across vectors. The return
value is always 2D; any structure of the input PDL (beyond using
the 0th dimension for vector index) is lost.
See also L</uniq> for a unique list of scalars; and
L<qsortvec|PDL::Ufunc/qsortvec> for sorting a list of vectors
lexicographcally.
=for bad
If a vector contains all bad values, it is ignored as in L</uniq>.
If some of the values are good, it is treated as a normal vector. For
example, [1 2 BAD] and [BAD 2 3] could be returned, but [BAD BAD BAD]
could not. Vectors containing BAD values will be returned after any
non-NaN and non-BAD containing vectors, followed by the NaN vectors.
=cut
sub PDL::uniqvec {
my($pdl) = shift;
return $pdl if ( $pdl->nelem == 0 || $pdl->ndims < 2 );
return $pdl if ( $pdl->slice("(0)")->nelem < 2 ); # slice isn't cheap but uniqvec isn't either
my $pdl2d = $pdl->clump(1..$pdl->ndims-1);
my $ngood = $pdl2d->ngoodover;
$pdl2d = $pdl2d->mv(0,-1)->dice($ngood->which)->mv(-1,0); # remove all-BAD vectors
my $numnan = ($pdl2d!=$pdl2d)->sumover; # works since no all-BADs to confuse
my $presrt = $pdl2d->mv(0,-1)->dice($numnan->not->which)->mv(0,-1); # remove vectors with any NaN values
my $nanvec = $pdl2d->mv(0,-1)->dice($numnan->which)->mv(0,-1); # the vectors with any NaN values
my $srt = $presrt->qsortvec->mv(0,-1); # BADs are sorted by qsortvec
my $srtdice = $srt;
my $somebad = null;
if ($srt->badflag) {
$srtdice = $srt->dice($srt->mv(0,-1)->nbadover->not->which);
$somebad = $srt->dice($srt->mv(0,-1)->nbadover->which);
}
my $uniq = $srtdice->nelem > 0
? ($srtdice != $srtdice->rotate(-1))->mv(0,-1)->orover->which
: $srtdice->orover->which;
my $ans = $uniq->nelem > 0 ? $srtdice->dice($uniq) :
($srtdice->nelem > 0) ? $srtdice->slice("0,:") :
$srtdice;
return $ans->append($somebad)->append($nanvec->mv(0,-1))->mv(0,-1);
}
EOPM
#####################################################################
# clipping routines
#####################################################################
# clipping
for my $opt (
['hclip','PDLMIN'],
['lclip','PDLMAX']
) {
my $name = $opt->[0];
my $op = $opt->[1];
my $code = '$c() = '.$op.'($b(), $a());';
pp_def(
$name,
HandleBad => 1,
Pars => 'a(); b(); [o] c()',
Code =>
'PDL_IF_BAD(if ( $ISBAD(a()) || $ISBAD(b()) ) {
$SETBAD(c());
} else,) { '.$code.' }',
Doc => 'clip (threshold) C<$a> by C<$b> (C<$b> is '.
($name eq 'hclip' ? 'upper' : 'lower').' bound)',
PMCode=>pp_line_numbers(__LINE__, <<"EOD"),
sub PDL::$name {
my (\$x,\$y) = \@_;
my \$c;
if (\$x->is_inplace) {
\$x->set_inplace(0); \$c = \$x;
} elsif (\@_ > 2) {\$c=\$_[2]} else {\$c=PDL->nullcreate(\$x)}
PDL::_${name}_int(\$x,\$y,\$c);
return \$c;
}
EOD
); # pp_def $name
} # for: my $opt
pp_add_exported('', 'clip');
pp_addpm(<<'EOD');
=head2 clip
=for ref
Clip (threshold) an ndarray by (optional) upper or lower bounds.
=for usage
$y = $x->clip(0,3);
$c = $x->clip(undef, $x);
=for bad
clip handles bad values since it is just a
wrapper around L</hclip> and
L</lclip>.
=cut
EOD
pp_def(
'clip',
HandleBad => 1,
Pars => 'a(); l(); h(); [o] c()',
Code => <<'EOBC',
PDL_IF_BAD(
if( $ISBAD(a()) || $ISBAD(l()) || $ISBAD(h()) ) {
$SETBAD(c());
} else,) {
$c() = PDLMIN($h(), PDLMAX($l(), $a()));
}
EOBC
PMCode=>pp_line_numbers(__LINE__, <<'EOPM'),
*clip = \&PDL::clip;
sub PDL::clip {
my($x, $l, $h) = @_;
my $d;
unless(defined($l) || defined($h)) {
# Deal with pathological case
if($x->is_inplace) {
$x->set_inplace(0);
return $x;
} else {
return $x->copy;
}
}
if($x->is_inplace) {
$x->set_inplace(0); $d = $x
} elsif (@_ > 3) {
$d=$_[3]
} else {
$d = PDL->nullcreate($x);
}
if(defined($l) && defined($h)) {
PDL::_clip_int($x,$l,$h,$d);
} elsif( defined($l) ) {
PDL::_lclip_int($x,$l,$d);
} elsif( defined($h) ) {
PDL::_hclip_int($x,$h,$d);
} else {
die "This can't happen (clip contingency) - file a bug";
}
return $d;
}
EOPM
); # end of clip pp_def call