-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathUfunc.pd
More file actions
1282 lines (1110 loc) · 35.2 KB
/
Ufunc.pd
File metadata and controls
1282 lines (1110 loc) · 35.2 KB
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(types ppdefs_complex ppdefs_all);
my $T = [map $_->ppsym, grep $_->integer, types];
my $A = [ppdefs_all];
pp_addpm({At=>'Top'},<<'EOD');
use strict;
use warnings;
=encoding utf8
=head1 NAME
PDL::Ufunc - primitive ufunc operations for pdl
=head1 DESCRIPTION
This module provides some primitive and useful functions defined
using PDL::PP based on functionality of what are sometimes called
I<ufuncs> (for example NumPY and Mathematica talk about these).
It collects all the functions generally used to C<reduce> or
C<accumulate> along a dimension. These all do their job across the
first dimension but by using the slicing functions you can do it
on any dimension.
The L<PDL::Reduce> module provides an alternative interface
to many of the functions in this module.
=head1 SYNOPSIS
use PDL::Ufunc;
=cut
use PDL::Slices;
use Carp;
EOD
# helper functions
sub projectdocs {
my $name = shift;
my $op = shift;
my $extras = shift;
<<EOD;
=for ref
Project via $name to N-1 dimensions
This function reduces the dimensionality of an ndarray
by one by taking the $name along the 1st dimension.
By using L<xchg|PDL::Slices/xchg> etc. it is possible to use
I<any> dimension.
$extras
EOD
} # sub: projectdocs()
sub cumuprojectdocs {
my $name = shift;
my $op = shift;
my $extras = shift;
<<EOD;
=for ref
Cumulative $name
This function calculates the cumulative $name
along the 1st dimension.
By using L<xchg|PDL::Slices/xchg> etc. it is possible to use
I<any> dimension.
The sum is started so that the first element in the cumulative $name
is the first element of the parameter.
$extras
EOD
} # sub: cumuprojectdocs()
my %over =
(
sumover => { name => 'sum', op => '+=', init => 0, },
prodover => { name => 'product', op => '*=', init => 1, leftzero => 'tmp == 0' },
);
foreach my $func ( sort keys %over ) {
my ($name, $op, $init, $leftzero) = @{$over{$func}}{qw(name op init leftzero)};
pp_def(
$_->[0].$func,
HandleBad => 1,
Pars => "a(n); $_->[1] [o]b();",
$_->[2] ? (GenericTypes=>$_->[2]) : (),
Code => <<EOF,
\$GENERIC(b) tmp = $init;
PDL_IF_BAD(int flag = 0;,)
loop(n) %{
PDL_IF_BAD(if ( \$ISBAD(a()) ) continue; flag = 1;,)
tmp $op \$a();
@{[$leftzero ? "if ($leftzero) break;" : '']}
%}
PDL_IF_BAD(if ( !flag ) \$SETBAD(b()); else,)
\$b() = tmp;
EOF
Doc => projectdocs( $name, $_->[0].$func, $_->[3] ),
) for (
['', 'int+', $A, ''],
['d', 'double', undef,
"Unlike L</$func>, the calculations are performed in double precision."
],
);
my $cfunc = "cumu${func}";
pp_def(
$_->[0].$cfunc,
HandleBad => 1,
Pars => "a(n); $_->[1] [o]b(n);",
$_->[2] ? (GenericTypes=>$_->[2]) : (),
Code => <<EOF,
\$GENERIC(b) tmp = $init;
loop(n) %{
PDL_IF_BAD(if ( \$ISBAD(a()) ) { \$SETBAD(b()); continue; },)
tmp $op \$a();
\$b() = tmp;
%}
EOF
Doc => cumuprojectdocs( $name, $_->[0].$cfunc, $_->[3] ),
) for (
['', 'int+', $A, ''],
['d', 'double', undef,
"Unlike L</$cfunc>, the calculations are performed in double precision."
],
);
} # foreach: my $func
%over = (
firstnonzeroover => { txt => 'first non-zero value', alltypes => 1,
op => 'tmp = $a();', leftzero => 'tmp' },
zcover => { def=>'char tmp', txt => '== 0', init => 1, alltypes => 1,
op => 'tmp &= ($a() == 0);', leftzero => '!tmp' },
andover => { def=>'char tmp', txt => 'logical and', init => 1, alltypes => 1,
op => 'tmp &= ($a() != 0);', leftzero => '!tmp' },
orover => { def=>'char tmp', txt => 'logical or', alltypes => 1,
op => 'tmp |= ($a() != 0);', leftzero => 'tmp' },
xorover => { def=>'char tmp', txt => 'logical xor', alltypes => 1,
op => 'tmp ^= ($a() != 0);', leftzero => 0 },
bandover => { txt => 'bitwise and', init => '~0',
op => 'tmp &= $a();', leftzero => '!tmp' },
borover => { txt => 'bitwise or',
op => 'tmp |= $a() ;', leftzero => '!~tmp' },
bxorover => { txt => 'bitwise xor',
op => 'tmp ^= $a() ;', leftzero => 0 },
);
foreach my $func ( sort keys %over ) {
my ($def,$txt,$init,$op,$leftzero) = @{$over{$func}}{qw(def txt init op leftzero)};
$def ||= '$GENERIC() tmp';
$init //= '0';
pp_def(
$func,
HandleBad => 1,
GenericTypes => $over{$func}{alltypes} ? [ppdefs_all] : $T,
Pars => 'a(n); [o] b()',
Code => pp_line_numbers(__LINE__, <<EOF),
$def = $init;
PDL_IF_BAD(int flag = 0;,)
loop(n) %{
PDL_IF_BAD(if ( \$ISBAD(a()) ) continue; flag = 1;,)
$op
if ( $leftzero ) break;
%}
PDL_IF_BAD(if (!flag) { \$SETBAD(b()); \$PDLSTATESETBAD(b); } else,)
\$b() = tmp;
EOF
Doc => projectdocs( $txt, $func,''),
BadDoc =>
'If C<a()> contains only bad data (and its bad flag is set),
C<b()> is set bad. Otherwise C<b()> will have its bad flag cleared,
as it will not contain any bad values.',
);
} # foreach: $func
pp_def('numdiff',
Pars => 'x(t); [o]dx(t)',
Inplace => 1,
GenericTypes => [ppdefs_all],
Code => <<'EOF',
/* do it in reverse so inplace works */
loop (t=::-1) %{
$dx() = t ? $x() - $x(t=>t-1) : $x();
%}
EOF
Doc => <<'EOF',
=for ref
Numerical differencing. DX(t) = X(t) - X(t-1), DX(0) = X(0).
Combined with C<slice('-1:0')>, can be used for backward differencing.
Unlike L</diff2>, output vector is same length.
Originally by Maggie J. Xiong.
Compare to L</cumusumover>, which acts as the converse of this.
See also L</diff2>, L</diffcentred>, L</partial>, L<PDL::Primitive/pchip_chim>.
EOF
);
pp_def('diffcentred',
HandleBad => 1,
Pars => 'a(n); [o]o(n)',
GenericTypes => [ppdefs_all],
Code => <<'EOF',
loop(n) %{
PDL_Indx left = n-1, right = n+1;
if (left < 0) left = $SIZE(n)-1;
if (right >= $SIZE(n)) right = 0;
PDL_IF_BAD(if ($ISBAD($a(n=>left)) || $ISBAD($a(n=>right))) {
$SETBAD(o()); continue;
},)
$o() = ($a(n=>right) - $a(n=>left))/2;
%}
EOF
Doc => <<'EOF',
=for ref
Calculates centred differences along a vector's 0th dimension.
Always periodic on boundaries; currently to change this, you must
pad your data, and/or trim afterwards. This is so that when using
with L</partial>, the size of data stays the same and therefore
compatible if differentiated along different dimensions, e.g.
calculating "curl".
By using L<PDL::Slices/xchg> etc. it is possible to use I<any> dimension.
See also L</diff2>, L</partial>, L</numdiff>, L<PDL::Primitive/pchip_chim>.
EOF
BadDoc => <<'EOF',
A bad value at C<n> means the affected output values at C<n-2>,C<n>
(if in boounds) are set bad.
EOF
);
pp_add_exported('partial');
pp_addpm(<<'EOF');
=head2 partial
=for ref
Take a numerical partial derivative along a given dimension, either
forward, backward, or centred.
See also L</numdiff>, L</diffcentred>,
L<PDL::Primitive/pchip_chim>, L<PDL::Primitive/pchip_chsp>,
and L<PDL::Slices/mv>, which are currently used to implement this.
Can be used to implement divergence and curl calculations (adapted
from Luis Mochán's work at
https://sourceforge.net/p/pdl/mailman/message/58843767/):
use v5.36;
use PDL;
sub curl ($f) {
my ($f0, $f1, $f2) = $f->using(0..2);
my $o = {dir=>'c'};
pdl(
$f2->partial(1,$o) - $f1->partial(2,$o),
$f0->partial(2,$o) - $f2->partial(0,$o),
$f1->partial(0,$o) - $f0->partial(1,$o),
)->mv(-1,0);
}
sub div ($f) {
my ($f0, $f1, $f2) = $f->using(0..2);
my $o = {dir=>'c'};
$f0->partial(0,$o) + $f1->partial(1,$o) + $f2->partial(2,$o);
}
sub trim3d ($f) { $f->slice(':,1:-2,1:-2,1:-2') } # adjust if change "dir"
my $z=zeroes(5,5,5);
my $v=pdl(-$z->yvals, $z->xvals, $z->zvals)->mv(-1,0);
say trim3d(curl($v));
say div($v);
=for usage
$pdl->partial(2); # along dim 2, centred
$pdl->partial(2, {d=>'c'}); # along dim 2, centred
$pdl->partial(2, {d=>'f'}); # along dim 2, forward
$pdl->partial(2, {d=>'b'}); # along dim 2, backward
$pdl->partial(2, {d=>'p'}); # along dim 2, piecewise cubic Hermite
$pdl->partial(2, {d=>'s'}); # along dim 2, cubic spline
=cut
my %dirtype2func = (
f => \&numdiff,
b => sub { $_[0]->slice('-1:0')->numdiff },
c => \&diffcentred,
p => sub {(PDL::Primitive::pchip_chim($_[0]->xvals, $_[0]))[0]},
s => sub {(PDL::Primitive::pchip_chsp([0,0], [0,0], $_[0]->xvals, $_[0]))[0]},
);
*partial = \&PDL::partial;
sub PDL::partial {
my ($f, $dim, $opts) = @_;
$opts ||= {};
my $difftype = $opts->{dir} || $opts->{d} || 'c';
my $func = $dirtype2func{$difftype} || barf "partial: unknown 'dir' option '$difftype', only know (@{[sort keys %dirtype2func]})";
$f = $f->mv($dim, 0) if $dim;
my $ret = $f->$func;
$dim ? $ret->mv(0, $dim) : $ret;
}
EOF
pp_def('diff2',
HandleBad => 1,
Pars => 'a(n); [o]o(nminus1=CALC($SIZE(n) - 1))',
GenericTypes => [ppdefs_all],
Code => <<'EOF',
$GENERIC() lastval = PDL_IF_BAD($ISBAD($a(n=>0)) ? 0 :,) $a(n=>0);
loop(n=1) %{
PDL_IF_BAD(if ($ISBAD($a()))
$SETBAD(o(nminus1=>n-1));
else,)
$o(nminus1=>n-1) = $a() - lastval;
PDL_IF_BAD(if ($ISGOOD($a())),) lastval = $a();
%}
EOF
Doc => <<'EOF',
=for ref
Numerically forward differentiates a vector along 0th dimension.
By using L<PDL::Slices/xchg> etc. it is possible to use I<any> dimension.
Unlike L</numdiff>, output vector is one shorter.
Combined with C<slice('-1:0')>, can be used for backward differencing.
See also L</numdiff>, L</diffcentred>, L</partial>, L<PDL::Primitive/pchip_chim>.
=for example
print pdl(q[3 4 2 3 2 3 1])->diff2;
# [1 -2 1 -1 1 -2]
EOF
BadDoc => <<'EOF',
On bad value, output value is set bad. On next good value, output value
is difference between that and last good value.
EOF
);
# this would need a lot of work to support bad values
# plus it gives me a chance to check out HandleBad => 0 ;)
#
pp_def('intover',
HandleBad => 0,
Pars => 'a(n); float+ [o]b();',
Code =>
'/* Integration formulae from Press et al 2nd Ed S 4.1 */
switch ($SIZE(n)) {
case 1:
broadcastloop %{
$b() = 0.; /* not a(n=>0); as interval has zero width */
%}
break;
case 2:
broadcastloop %{
$b() = 0.5*($a(n=>0)+$a(n=>1));
%}
break;
case 3:
broadcastloop %{
$b() = ($a(n=>0)+4*$a(n=>1)+$a(n=>2))/3.;
%}
break;
case 4:
broadcastloop %{
$b() = ($a(n=>0)+$a(n=>3)+3.*($a(n=>1)+$a(n=>2)))*0.375;
%}
break;
case 5:
broadcastloop %{
$b() = (14.*($a(n=>0)+$a(n=>4))
+64.*($a(n=>1)+$a(n=>3))
+24.*$a(n=>2))/45.;
%}
break;
default:
broadcastloop %{
$GENERIC(b) tmp = 0;
loop (n=3:-3) %{ tmp += $a(); %}
loop (n=-3:-2) %{ tmp += (23./24.)*($a(n=>2)+$a()); %}
loop (n=-2:-1) %{ tmp += (7./6.) *($a(n=>1)+$a()); %}
loop (n=-1:) %{ tmp += (3./8.) *($a(n=>0)+$a()); %}
$b() = tmp;
%}
}
',
Doc => projectdocs('integral','intover', <<'EOF'),
Notes:
C<intover> uses a point spacing of one (i.e., delta-h==1). You will
need to scale the result to correct for the true point delta.
For C<n E<gt> 3>, these are all C<O(h^4)> (like Simpson's rule), but are
integrals between the end points assuming the pdl gives values just at
these centres: for such `functions', sumover is correct to C<O(h)>, but
is the natural (and correct) choice for binned data, of course.
EOF
); # intover
sub synonym {
my ($name, $synonym) = @_;
pp_add_exported('', $synonym);
pp_addpm(
"=head2 $synonym\n\n=for ref\n\nSynonym for L</$name>.\n\n=cut\n
*PDL::$synonym = *$synonym = \\&PDL::$name;"
);
}
sub make_average {
my ($prefix, $outpar_type, $extra) = @_;
pp_def("${prefix}average",
HandleBad => 1,
Pars => "a(n); $outpar_type [o]b();",
Code => <<'EOF',
$GENERIC(b) tmp = 0;
PDL_Indx cnt = 0;
loop(n) %{
PDL_IF_BAD(if ( $ISBAD(a()) ) continue;,)
cnt++;
tmp += $a();
%}
if ( !cnt ) {
PDL_IF_BAD($SETBAD(b()), $b() = PDL_IF_GENTYPE_INTEGER(0,NAN));
} else
$b() = tmp / cnt;
EOF
Doc => projectdocs( 'average', "${prefix}average", $extra||'' ),
);
synonym(map "$prefix$_", qw(average avgover));
}
make_average('', 'int+');
make_average('c', 'cdouble',
"Unlike L<average|/average>, the calculation is performed in complex double
precision."
);
make_average('d', 'double',
"Unlike L<average|/average>, the calculation is performed in double
precision."
);
for my $which (
[qw(minimum < minover)],
[qw(maximum > maxover)],
) {
my ($name, $op, $synonym) = @$which;
pp_def($name,
HandleBad => 1,
Pars => 'a(n); [o]c();',
Code =>
'$GENERIC() cur = 0;
int flag = 0;
loop(n) %{
PDL_IF_BAD(if ($ISBAD(a())) continue;,)
if ( flag && !($a() '.$op.' cur) && !PDL_ISNAN_$PPSYM()(cur) ) continue;
cur = $a(); flag = 1;
%}
if ( flag ) { $c() = cur; }
else { $SETBAD(c()); $PDLSTATESETBAD(c); }',
Doc => projectdocs($name,$name,''),
BadDoc =>
'Output is set bad if no elements of the input are non-bad,
otherwise the bad flag is cleared for the output ndarray.
Note that C<NaNs> are considered to be valid values and will "win" over non-C<NaN>;
see L<isfinite|PDL::Math/isfinite> and L<badmask|PDL::Bad/badmask>
for ways of masking NaNs.
',
);
synonym($name, $synonym);
pp_def("${name}_ind",
HandleBad => 1,
Pars => 'a(n); indx [o] c();',
Code =>
'$GENERIC() cur = 0;
PDL_Indx curind = -1;
loop(n) %{
PDL_IF_BAD(if ($ISBAD(a())) continue;,)
if (curind != -1 && !($a() '.$op.' cur) && !PDL_ISNAN_$PPSYM()(cur)) continue;
cur = $a(); curind = n;
%}
if ( curind != -1 ) { $c() = curind; }
else { $SETBAD(c()); $PDLSTATESETBAD(c); }',
Doc => "Like $name but returns the first matching index rather than the value",
BadDoc =>
'Output is set bad if no elements of the input are non-bad,
otherwise the bad flag is cleared for the output ndarray.
Note that C<NaNs> are considered to be valid values and will "win" over non-C<NaN>;
see L<isfinite|PDL::Math/isfinite> and L<badmask|PDL::Bad/badmask>
for ways of masking NaNs.
',
);
synonym("${name}_ind", "${synonym}_ind");
pp_def("${name}_n_ind",
HandleBad => 1,
Pars => 'a(n); indx [o]c(m);',
OtherPars => 'PDL_Indx m_size => m;',
PMCode => PDL::PP::pp_line_numbers(__LINE__, <<EOF),
sub PDL::${name}_n_ind {
my (\$a, \$c, \$m_size) = \@_;
\$m_size //= ref(\$c) ? \$c->dim(0) : \$c; # back-compat with pre-2.077
my \$set_out = 1;
\$set_out = 0, \$c = null if !ref \$c;
\$c = \$c->indx if !\$c->isnull;
PDL::_${name}_n_ind_int(\$a, \$c, \$m_size);
\$set_out ? \$_[1] = \$c : \$c;
}
EOF
RedoDimsCode => 'if($SIZE(m) > $SIZE(n)) $CROAK("m_size > n_size");',
Code =>
'$GENERIC() cur = 0; PDL_Indx curind; register PDL_Indx ns = $SIZE(n);
$PDLSTATESETGOOD(c);
loop(m) %{
curind = ns;
loop(n) %{
PDL_Indx outer_m = m; int flag=0;
loop (m=:outer_m) %{
if ($c() == n) {flag=1; break;}
%}
if (!flag &&
PDL_IF_BAD($ISGOOD(a()) &&,)
((curind == ns) || $a() '.$op.' cur || PDL_ISNAN_$PPSYM()(cur)))
{cur = $a(); curind = n;}
%}
if (curind != ns) { $c() = curind; }
else { $SETBAD(c()); $PDLSTATESETBAD(c); }
%}',
Doc => <<EOF,
=for ref
Returns the index of first C<m_size> $name elements. As of 2.077, you can
specify how many by either passing in an ndarray of the given size
(DEPRECATED - will be converted to indx if needed and the input arg will
be set to that), or just the size, or a null and the size.
=for usage
${name}_n_ind(\$pdl, \$out = zeroes(5)); # DEPRECATED
\$out = ${name}_n_ind(\$pdl, 5);
${name}_n_ind(\$pdl, \$out = null, 5);
EOF
BadDoc =>
'Output bad flag is cleared for the output ndarray if sufficient non-bad elements found,
else remaining slots in C<$c()> are set bad.
Note that C<NaNs> are considered to be valid values and will "win" over non-C<NaN>;
see L<isfinite|PDL::Math/isfinite> and L<badmask|PDL::Bad/badmask>
for ways of masking NaNs.
',
);
synonym("${name}_n_ind", "${synonym}_n_ind");
} # foreach: $which
pp_def('minmaximum',
HandleBad => 1,
Pars => 'a(n); [o]cmin(); [o] cmax(); indx [o]cmin_ind(); indx [o]cmax_ind();',
Code => <<'EOF',
$GENERIC() curmin = 0, curmax = 0; /* Handle null ndarray --CED */
PDL_Indx curmin_ind = 0, curmax_ind = 0; int flag = 0;
loop(n) %{
PDL_IF_BAD(if ($ISBAD(a())) continue;,)
if (PDL_ISNAN_$PPSYM()($a())) continue;
if (!flag) {
curmin = curmax = $a();
curmin_ind = curmax_ind = n;
flag = 1;
} else {
if ($a() < curmin) { curmin = $a(); curmin_ind = n; }
if ($a() > curmax) { curmax = $a(); curmax_ind = n; }
}
%}
if ( !flag ) { /* Handle null ndarray */
$SETBAD(cmin()); $SETBAD(cmin_ind());
$SETBAD(cmax()); $SETBAD(cmax_ind());
$PDLSTATESETBAD(cmin); $PDLSTATESETBAD(cmin_ind);
$PDLSTATESETBAD(cmax); $PDLSTATESETBAD(cmax_ind);
} else {
$cmin() = curmin; $cmin_ind() = curmin_ind;
$cmax() = curmax; $cmax_ind() = curmax_ind;
}
EOF
Doc => '
=for ref
Find minimum and maximum and their indices for a given ndarray;
=for example
pdl> $x=pdl [[-2,3,4],[1,0,3]]
pdl> ($min, $max, $min_ind, $max_ind)=minmaximum($x)
pdl> p $min, $max, $min_ind, $max_ind
[-2 0] [4 3] [0 1] [2 2]
See also L</minmax>, which clumps the ndarray together.
=cut
',
BadDoc =>
'If C<a()> contains only bad data, then the output ndarrays will
be set bad, along with their bad flag.
Otherwise they will have their bad flags cleared,
since they will not contain any bad values.',
); # pp_def minmaximum
synonym(qw(minmaximum minmaxover));
# Generate small ops functions to do entire array
# How to handle a return value of BAD - ie what
# datatype to use?
for my $op ( ['avg','average','average'],
['sum','sumover','sum'],
['prod','prodover','product'],
['davg','daverage','average (in double precision)'],
['dsum','dsumover','sum (in double precision)'],
['dprod','dprodover','product (in double precision)'],
['zcheck','zcover','check for zero'],
['and','andover','logical and'],
['band','bandover','bitwise and'],
['or','orover','logical or'],
['bor','borover','bitwise or'],
['xorall','xorover','logical xor'],
['bxor','bxorover','bitwise xor'],
['min','minimum','minimum'],
['max','maximum','maximum'],
['median', 'medover', 'median'],
['mode', 'modeover', 'mode'],
['oddmedian','oddmedover','oddmedian']) {
my ($name, $func, $text) = @$op;
pp_add_exported('', $name);
pp_addpm(<<"EOD");
=head2 $name
=for ref
Return the $text of all elements in an ndarray.
See the documentation for L</$func> for more information.
=for usage
\$x = $name(\$data);
=for bad
This routine handles bad values.
=cut
*$name = \\&PDL::$name;
sub PDL::$name { \$_[0]->flat->${func} }
EOD
} # for $op
pp_add_exported('','any all');
pp_addpm(<<'EOPM');
=head2 any
=for ref
Return true if any element in ndarray set
Useful in conditional expressions:
=for example
if (any $x>15) { print "some values are greater than 15\n" }
=for bad
See L</or> for comments on what happens when all elements
in the check are bad.
=cut
*any = \∨
*PDL::any = \&PDL::or;
=head2 all
=for ref
Return true if all elements in ndarray set
Useful in conditional expressions:
=for example
if (all $x>15) { print "all values are greater than 15\n" }
=for bad
See L</and> for comments on what happens when all elements
in the check are bad.
=cut
*all = \∧
*PDL::all = \&PDL::and;
=head2 minmax
=for ref
Returns a list with minimum and maximum values of an ndarray.
=for usage
($mn, $mx) = minmax($pdl);
This routine does I<not> broadcast over the dimensions of C<$pdl>;
it returns the minimum and maximum values of the whole ndarray.
See L</minmaximum> if this is not what is required.
The two values are returned as Perl scalars,
and therefore ignore whether the values are bad.
=for example
pdl> $x = pdl [1,-2,3,5,0]
pdl> ($min, $max) = minmax($x);
pdl> p "$min $max\n";
-2 5
=cut
*minmax = \&PDL::minmax;
sub PDL::minmax { map $_->sclr, ($_[0]->flat->minmaximum)[0,1] }
EOPM
pp_add_exported('', 'minmax');
my $chdr_qsort = 'PDL_TYPELIST_REAL(PDL_QSORT)';
my $chdr_qsorti = PDL::PP::pp_line_numbers(__LINE__, <<'EOF');
#define X(symbol, ctype, ppsym, ...) \
static inline void qsort_ind_ ## ppsym(ctype* xx, PDL_Indx* ix, PDL_Indx a, PDL_Indx b) { \
PDL_Indx i,j; \
PDL_Indx t; \
ctype median; \
i = a; j = b; \
median = xx[ix[(i+j) / 2]]; \
do { \
while (xx[ix[i]] < median) \
i++; \
while (median < xx[ix[j]]) \
j--; \
if (i <= j) { \
t = ix[i]; ix[i] = ix[j]; ix[j] = t; \
i++; j--; \
} \
} while (i <= j); \
if (a < j) \
qsort_ind_ ## ppsym(xx,ix,a,j); \
if (i < b) \
qsort_ind_ ## ppsym(xx,ix,i,b); \
}
PDL_TYPELIST_REAL(X)
#undef X
EOF
my $chdr_qsortvec_def = PDL::PP::pp_line_numbers(__LINE__, <<'EOF');
#define X(symbol, ctype, ppsym, ...) \
/******* \
* qsortvec helper routines \
* --CED 21-Aug-2003 \
*/ \
/* Compare a vector in lexicographic order, return equivalent of "<=>". \
*/ \
static inline signed int pdl_cmpvec_ ## ppsym(ctype *a, ctype *b, PDL_Indx n) { \
PDL_Indx i; \
for(i=0; i<n; a++,b++,i++) { \
if( *a < *b ) return -1; \
if( *a > *b ) return 1; \
} \
return 0; \
}
PDL_TYPELIST_REAL(X)
#undef X
#define PDL_QSORTVEC(ppsym, RECURSE, INDEXTERM, swapcode) \
PDL_Indx i,j, median_ind; \
i = a; \
j = b; \
median_ind = (i+j)/2; \
do { \
while( pdl_cmpvec_ ## ppsym( &(xx[n*INDEXTERM(i)]), &(xx[n*INDEXTERM(median_ind)]), n ) < 0 ) \
i++; \
while( pdl_cmpvec_ ## ppsym( &(xx[n*INDEXTERM(j)]), &(xx[n*INDEXTERM(median_ind)]), n ) > 0 ) \
j--; \
if(i<=j) { \
PDL_Indx k; \
swapcode \
if (median_ind==i) \
median_ind=j; \
else if (median_ind==j) \
median_ind=i; \
i++; \
j--; \
} \
} while (i <= j); \
if (a < j) \
RECURSE( ppsym, a, j ); \
if (i < b) \
RECURSE( ppsym, i, b );
EOF
my $chdr_qsortvec = PDL::PP::pp_line_numbers(__LINE__, <<'EOF');
#define PDL_QSORTVEC_INDEXTERM(indexterm) indexterm
#define PDL_QSORTVEC_RECURSE(ppsym, ...) pdl_qsortvec_ ## ppsym(xx, n, __VA_ARGS__)
#define X(symbol, ctype, ppsym, ...) \
static inline void pdl_qsortvec_ ## ppsym(ctype *xx, PDL_Indx n, PDL_Indx a, PDL_Indx b) { \
PDL_QSORTVEC(ppsym, PDL_QSORTVEC_RECURSE, PDL_QSORTVEC_INDEXTERM, \
ctype *aa = &xx[n*i]; \
ctype *bb = &xx[n*j]; \
for( k=0; k<n; aa++,bb++,k++ ) { \
ctype z = *aa; \
*aa = *bb; \
*bb = z; \
} \
) \
}
PDL_TYPELIST_REAL(X)
#undef X
#undef PDL_QSORTVEC_INDEXTERM
#undef PDL_QSORTVEC_RECURSE
EOF
my $chdr_qsortvec_ind = PDL::PP::pp_line_numbers(__LINE__, <<'EOF');
#define PDL_QSORTVEC_INDEXTERM(indexterm) ix[indexterm]
#define PDL_QSORTVEC_RECURSE(ppsym, ...) pdl_qsortvec_ind_ ## ppsym(xx, ix, n, __VA_ARGS__)
#define X(symbol, ctype, ppsym, ...) \
static inline void pdl_qsortvec_ind_ ## ppsym(ctype *xx, PDL_Indx *ix, PDL_Indx n, PDL_Indx a, PDL_Indx b) { \
PDL_QSORTVEC(ppsym, PDL_QSORTVEC_RECURSE, PDL_QSORTVEC_INDEXTERM, \
k = ix[i]; \
ix[i] = ix[j]; \
ix[j] = k; \
) \
}
PDL_TYPELIST_REAL(X)
#undef X
#undef PDL_QSORTVEC_INDEXTERM
#undef PDL_QSORTVEC_RECURSE
EOF
# when copying the data over to the temporary array,
# ignore the bad values and then only send the number
# of good elements to the sort routines
# should use broadcastloop ?
my $copy_to_temp = pp_line_numbers(__LINE__, '
if ($PDL(a)->nvals == 0)
$CROAK("cannot process empty ndarray");
PDL_Indx nn = PDL_IF_BAD(0,$SIZE(n)-1);
loop(n) %{
PDL_IF_BAD(if ( $ISGOOD(a()) ) { $tmp(n=>nn) = $a(); nn++; },
$tmp() = $a();)
%}
PDL_IF_BAD(if ( nn == 0 ) {
$SETBAD(b());
} else {
nn -= 1;,{)
qsort_$PPSYM() ($P(tmp), 0, nn);');
my $find_median_average = '
PDL_Indx nn1 = nn/2, nn2 = nn1+1;
if (nn%2==0) {
$b() = $tmp(n => nn1);
}
else {
$b() = 0.5*( $tmp(n => nn1) + $tmp(n => nn2) );
}';
pp_def('medover',
HandleBad => 1,
Pars => 'a(n); [o]b(); [t]tmp(n);',
Doc => projectdocs('median','medover',''),
CHeader => 'PDL_TYPELIST_REAL(PDL_QSORT)',
Code => $copy_to_temp . $find_median_average . '}',
); # pp_def: medover
my $find_median_lower = '
PDL_Indx nn1 = nn/2;
$b() = $tmp(n => nn1);';
pp_def('oddmedover',
HandleBad => 1,
Pars => 'a(n); [o]b(); [t]tmp(n);',
Doc => projectdocs('oddmedian','oddmedover','
The median is sometimes not a good choice as if the array has
an even number of elements it lies half-way between the two
middle values - thus it does not always correspond to a data
value. The lower-odd median is just the lower of these two values
and so it ALWAYS sits on an actual data value which is useful in
some circumstances.
'),
CHeader => 'PDL_TYPELIST_REAL(PDL_QSORT)',
Code => $copy_to_temp . $find_median_lower . '}',
); # pp_def: oddmedover
pp_def('modeover',
HandleBad=>undef,
Pars => 'data(n); [o]out(); [t]sorted(n);',
GenericTypes=>$T,
Doc=>projectdocs('mode','modeover','
The mode is the single element most frequently found in a
discrete data set.
It I<only> makes sense for integer data types, since
floating-point types are demoted to integer before the
mode is calculated.
C<modeover> treats BAD the same as any other value: if
BAD is the most common element, the returned value is also BAD.
'),
CHeader => 'PDL_TYPELIST_INTEGER(PDL_QSORT)',
Code => <<'EOCODE',
PDL_Indx i = 0;
PDL_Indx most = 0;
$GENERIC() curmode = 0;
$GENERIC() curval = 0;
/* Copy input to buffer for sorting, and sort it */
loop(n) %{ $sorted() = $data(); %}
qsort_$PPSYM()($P(sorted),0,$SIZE(n)-1);
/* Walk through the sorted data and find the most common elemen */
loop(n) %{
if( n==0 || curval != $sorted() ) {
curval = $sorted();
i=0;
} else {
i++;
if(i>most){
most=i;
curmode = curval;
}
}
%}
$out() = curmode;
EOCODE
);
my $find_pct_interpolate = '
double np, pp1, pp2;
np = nn * $p();
PDL_Indx nn1 = PDLMIN(nn,PDLMAX(0,np));
PDL_Indx nn2 = PDLMIN(nn,PDLMAX(0,np+1));
if (nn == 0) {
pp1 = 0;
pp2 = 0;
} else {
pp1 = (double)nn1/(double)(nn);
pp2 = (double)nn2/(double)(nn);
}
if ( np <= 0.0 ) {
$b() = $tmp(n => 0);
} else if ( np >= nn ) {
$b() = $tmp(n => nn);
} else if ($tmp(n => nn2) == $tmp(n => nn1)) {
$b() = $tmp(n => nn1);
} else if ($p() == pp1) {
$b() = $tmp(n => nn1);
} else if ($p() == pp2) {
$b() = $tmp(n => nn2);
} else {
$b() = (np - nn1)*($tmp(n => nn2) - $tmp(n => nn1)) + $tmp(n => nn1);
}
';
pp_def('pctover',
HandleBad => 1,
Pars => 'a(n); p(); [o]b(); [t]tmp(n);',
Doc => projectdocs('specified percentile', 'pctover',
'The specified
percentile must be between 0.0 and 1.0. When the specified percentile
falls between data points, the result is interpolated. Values outside
the allowed range are clipped to 0.0 or 1.0 respectively. The algorithm
implemented here is based on the interpolation variant described at
L<http://en.wikipedia.org/wiki/Percentile> as used by Microsoft Excel
and recommended by NIST.
'),
CHeader => 'PDL_TYPELIST_REAL(PDL_QSORT)',
Code => $copy_to_temp . $find_pct_interpolate . '}',
);
pp_def('oddpctover',
HandleBad => 1,