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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737
|
sub defpdl {
my %hash = (Pars => $_[1],
OtherPars => $_[2],
Code => $_[3]);
$hash{Doc} = $_[4] if $#_>3;
pp_def($_[0],%hash);
}
pp_addhdr(<<'EOD');
#define IsNaN(x) (x != x)
#ifndef RAND_MAX
#error "You must have a working RAND_MAX! Something's wrong with your include files"
#endif
EOD
pp_addpm({At=>Top},<<'EOD');
use PDL::Slices;
use Carp;
=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
use PDL::Primitive;
=cut
EOD
sub projectdocs {
my $name = shift;
my $op = shift;
my $extras = shift;
return <<EOD;
=for ref
Project via $name to N-1 dimensions
This function reduces the dimensionality of a piddle
by one by taking the $name along the 1st dimension.
By using C<xchg> etc. (see L<PDL::Slices>) it is possible to use
I<any> dimension.
=for usage
\$a = $op(\$b);
=for example
\$spectrum = $op \$image->xchg(0,1)
$extras
=cut
EOD
}
sub cumuprojectdocs {
my $name = shift;
my $op = shift;
my $extras = shift;
return <<EOD;
=for ref
Cumulative $name
This function calculates the cumulative $name
along the 1st dimension.
By using C<xchg> etc. (see L<PDL::Slices>) 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.
=for usage
\$a = $op(\$b);
=for example
\$spectrum = $op \$image->xchg(0,1)
$extras
=cut
EOD
}
defpdl(
'sumover',
'a(n); int+ [o]b();',
'',
'$GENERIC(b) tmp = 0;
loop(n) %{ tmp += $a(); %}
$b() = tmp;',
projectdocs('sum','sumover','')
);
defpdl(
'zcover',
'a(n); int+ [o]b();',
'',
'$GENERIC(b) tmp = 1;
loop(n) %{ tmp = tmp && $a() == 0; if (!tmp) break; %}
$b() = tmp;',
projectdocs('!= 0','zcover','')
);
pp_def(
'andover',
Pars => 'a(n); int+ [o]b();',
GenericTypes => [B,S,U,L],
Code => '$GENERIC(b) tmp = 1;
loop(n) %{ tmp = tmp && $a(); if (!tmp) break; %}
$b() = tmp;',
Doc => projectdocs('and','andover','')
);
pp_def(
'bandover',
Pars => 'a(n); int+ [o]b();',
GenericTypes => [B,S,U,L],
Code => '$GENERIC(b) tmp = ~ 0 ;
loop(n) %{ tmp &= $a(); if (!tmp) break; %}
$b() = tmp;',
Doc => projectdocs('bitwise and','bandover','')
);
pp_def(
'orover',
Pars => 'a(n); int+ [o]b();',
GenericTypes => [B,S,U,L],
Code => '$GENERIC(b) tmp = 0;
loop(n) %{ tmp = tmp || $a(); if (tmp) break; %}
$b() = tmp;',
Doc => projectdocs('or','orover','')
);
pp_def(
'borover',
Pars => 'a(n); int+ [o]b();',
GenericTypes => [B,S,U,L],
Code => '$GENERIC(b) tmp = 0;
loop(n) %{ tmp |= $a(); if (!~tmp) break; %}
$b() = tmp;',
Doc => projectdocs('bitwise or','borover','')
);
defpdl(
'intover',
'a(n); int+ [o]b();',
'',
'$GENERIC(b) tmp = 0;
int ns = $SIZE(n), nn;
/* Integration formulae from Press et al 2nd Ed S 4.1 */
switch (ns) {
case 1:
threadloop %{
$b() = 0.; /* not a(n=>0); as interval has zero width */
%}
break;
case 2:
threadloop %{
$b() = 0.5*($a(n=>0)+$a(n=>1));
%}
break;
case 3:
threadloop %{
$b() = ($a(n=>0)+4*$a(n=>1)+$a(n=>2))/3.;
%}
break;
case 4:
threadloop %{
$b() = ($a(n=>0)+$a(n=>3)+3.*($a(n=>1)+$a(n=>2)))*0.375;
%}
break;
case 5:
threadloop %{
$b() = (14.*($a(n=>0)+$a(n=>4))
+64.*($a(n=>1)+$a(n=>3))
+24.*$a(n=>2))/45.;
%}
break;
default:
threadloop %{
for (nn=3;nn<ns-3;nn++) { tmp += $a(n=>nn); }
tmp += (23./24.)*($a(n=>2)+$a(n=>nn));nn++;
tmp += (7./6.) *($a(n=>1)+$a(n=>nn));nn++;
tmp += 0.375 *($a(n=>0)+$a(n=>nn));
$b() = tmp;
%}
}
',
projectdocs('integral','intover',
q~Notes:
For n > 3, these are all 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 O(h), but
is the natural (and correct) choice for binned data, of course.
~)
);
defpdl(
'cumusumover',
'a(n); int+ [o]b(n);',
'',
'$GENERIC(b) tmp = 0;
loop(n) %{ tmp += $a();
$b() = tmp;
%}
',
cumuprojectdocs('sum','cumusumover','')
);
defpdl(
'prodover',
'a(n); int+ [o]b();',
'',
'$GENERIC(b) tmp = 1;
loop(n) %{ tmp *= $a(); %}
$b() = tmp;',
projectdocs('product','prodover','')
);
defpdl(
'cumuprodover',
'a(n); int+ [o]b(n);',
'',
'$GENERIC(b) tmp = 1;
loop(n) %{ tmp *= $a();
$b() = tmp;
%}
',
cumuprojectdocs('product','cumuprodover','')
);
# XXX why cnt? Why not size(n)? Why not threadloop for efficiency
defpdl(
'average',
'a(n); int+ [o]b();',
'',
'$GENERIC(b) tmp = 0, cnt;
cnt = 0;
loop(n) %{ tmp += $a(); cnt++; %}
$b() = tmp/cnt;',
projectdocs('average','average','')
);
# Internal utility sorting routine for median/qsort routines.
for (keys %PDL::Types::typehash) {
$ctype = $PDL::Types::typehash{$_}{ctype};
$ppsym = $PDL::Types::typehash{$_}{ppsym};
pp_addhdr("
void pdl_qsort_$ppsym($ctype* xx, int a, int b) {
int i,j;
$ctype t, median;
i = a; j = b;
median = xx[(i+j) / 2];
do {
while (xx[i] < median)
i++;
while (median < xx[j])
j--;
if (i <= j) {
t = xx[i]; xx[i] = xx[j]; xx[j] = t;
i++; j--;
}
} while (i <= j);
if (a < j)
pdl_qsort_$ppsym(xx,a,j);
if (i < b)
pdl_qsort_$ppsym(xx,i,b);
}
void pdl_qsort_ind_$ppsym($ctype* xx, int* ix, int a, int b) {
int i,j;
int 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)
pdl_qsort_ind_$ppsym(xx,ix,a,j);
if (i < b)
pdl_qsort_ind_$ppsym(xx,ix,i,b);
}
");
}
pp_def('medover',
Pars => 'a(n); [o]b(); [t]tmp(n);',
Doc => projectdocs('median','medover',''),
Code => '
int nn, nn1, nn2;
loop(n) %{ $tmp() = $a(); %}
nn = $COMP(__n_size)-1;
$TBSULFD(pdl_qsort_B,pdl_qsort_S,pdl_qsort_U,
pdl_qsort_L,pdl_qsort_F,pdl_qsort_D) ($P(tmp), 0, nn);
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('oddmedover',
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.
'),
Code => '
int nn, nn1;
loop(n) %{ $tmp() = $a(); %}
nn = $COMP(__n_size)-1;
$TBSULFD(pdl_qsort_B,pdl_qsort_S,pdl_qsort_U,
pdl_qsort_L,pdl_qsort_F,pdl_qsort_D) ($P(tmp), 0, nn);
nn1 = nn/2;
$b() = $tmp(n => nn1);
');
# Generate small ops functions to do entire array
for $op ( ['avg','average','average'],
['sum','sumover','sum'],
['zcheck','zcover','check for zero'],
['and','andover','logical and'],
['band','bandover','bitwise and'],
['or','orover','logical or'],
['bor','borover','bitwise or'],
['min','minimum','minimum'],
['max','maximum','maximum'],
['median', 'medover', 'median'],
['oddmedian','oddmedover','oddmedian']) {
pp_add_exported('', $op->[0]);
pp_addpm(<<"EOD");
=head2 $op->[0]
=for ref
Return the $op->[2] of all elements in a piddle
=for usage
\$x = $op->[0](\$data);
=cut
*$op->[0] = \\&PDL::$op->[0];
sub PDL::$op->[0] {
my(\$x) = \@_; my \$tmp;
\$x->clump(-1)->$op->[1](\$tmp=PDL->nullcreate(\$x) );
return \$tmp->at();
}
EOD
} # for $op
pp_add_exported('','any all');
pp_addpm(<<'EOPM');
=head2 any
=for ref
Return true if any element in piddle set
Useful in conditional expressions:
=for example
if (any $a>15) { print "some values are greater than 15\n" }
=cut
*any = \∨
*PDL::any = \&PDL::or;
=head2 all
=for ref
Return true if all elements in piddle set
Useful in conditional expressions:
=for example
if (all $a>15) { print "all values are greater than 15\n" }
=cut
*all = \∧
*PDL::all = \&PDL::and;
EOPM
pp_addpm(<<'EOD'
=head2 minmax
=for ref
Returns an array with minimum, maximum of a piddle.
=for usage
($mn, $mx) = minmax($pdl);
Return $mn as minimum, $mx as maximum, $mn_ind as the index of minimum and
$mx_ind as the index of the maximum.
=for example
perldl> $x = pdl [1,-2,3,5,0]
perldl> ($min, $max) = minmax($x);
perldl> p "$min $max\n";
=cut
*minmax = \&PDL::minmax;
sub PDL::minmax {
my ($x)=@_; my $tmp;
my @arr = $x->clump(-1)->minmaximum;
return @arr[0,1];
}
EOD
);
pp_add_exported('', 'minmax');
#pp_add_exported('', 'minmax_ind');
pp_def('qsort',
Pars => 'a(n); [o]b(n);',
Code => '
int nn;
loop(n) %{ $b() = $a(); %}
nn = $COMP(__n_size)-1;
$TBSULFD(pdl_qsort_B,pdl_qsort_S,pdl_qsort_U,
pdl_qsort_L,pdl_qsort_F,pdl_qsort_D) ($P(b), 0, nn);
', Doc=>'
=for ref
Quicksort a vector into ascending order.
=for example
print qsort random(10);
=cut
');
pp_def('qsorti',
Pars => 'a(n); int [o]indx(n);',
Code => '
int nn;
int i=0;
nn = $COMP(__n_size)-1;
loop(n) %{ $indx() = i++; %}
$TBSULFD(pdl_qsort_ind_B,pdl_qsort_ind_S,pdl_qsort_ind_U,
pdl_qsort_ind_L,pdl_qsort_ind_F,pdl_qsort_ind_D) ($P(a), $P(indx),
0, nn);
', Doc=>'
=for ref
Quicksort a vector and return index of elements in ascending order.
=for example
$ix = qsorti $a;
print $a->index($ix); # Sorted list
=cut
');
defpdl(
'axisvalues',
'[o,nc]a(n)',
'',
'loop(n) %{ $a() = n; %}',
'
=for ref
Internal routine
C<axisvalues> is the internal primitive that implements C<axisvals> and
alters its argument.
=cut
'
);
defpdl(
'inner',
'a(n); b(n); [o]c(); ', '',
'double tmp = 0;
loop(n) %{ tmp += $a() * $b(); %}
$c() = tmp;','
=for ref
Inner product over one dimension
c = sum_i a_i * b_i
');
defpdl(
'outer',
'a(n); b(m); [o]c(n,m); ', '',
'loop(n,m) %{ $c() = $a() * $b(); %}',
<<'EOD'
=for ref
outer product over one dimension
Naturally, it is possiblet to achieve the effects of outer
product simply by threading over the "C<*>"
operator but this function is provided for convenience.
=cut
EOD
);
pp_addpm(<<'EOD');
=head2 matmult
=for sig
Signature: matmult(a(x,y),b(y,z),[o]c(x,z))
=for ref
Matrix multiplication
We peruse the inner product to define matrix multiplication
via a threaded inner product
=cut
sub PDL::matmult {
barf "Invalid number of arguments for matmult" if $#_ < 1;
my ($a,$b,$c) = @_;
while ($a->getndims < 2) {$a = $a->dummy(-1)} # promote if necessary
while ($b->getndims < 2) {$b = $b->dummy(-1)}
if(!defined $c) {$c = PDL->nullcreate($a)}
$a->dummy(1)->inner($b->xchg(0,1)->dummy(2),$c);
return $c;
}
*matmult = \&PDL::matmult;
EOD
pp_add_exported('', 'matmult');
defpdl(
'innerwt',
'a(n); b(n); c(n); [o]d(); ', '',
'double tmp = 0;
loop(n) %{ tmp += $a() * $b() * $c(); %}
$d() = tmp;','
=for ref
Weighted (i.e. triple) inner product
d = sum_i a(i) b(i) c(i)
=cut
');
defpdl(
'inner2',
'a(n); b(n,m); c(m); [o]d();',
'',
'double tmp=0;
loop(n,m) %{
tmp += $a() * $b() * $c();
%}
$d() = tmp;
','
=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 thread over a and c since that would be very
wasteful. Instead, you should use a temporary for b*c.
=cut
');
defpdl(
'inner2d',
'a(n,m); b(n,m); [o]c()',
'',
'double tmp=0;
loop(n,m) %{
tmp += $a() * $b();
%}
$c() = tmp;
','
=for ref
Inner product over 2 dimensions.
Equivalent to
$c = inner($a->clump(2), $b->clump(2))
'
);
defpdl(
'inner2t',
'a(j,n); b(n,m); c(m,k); [t]tmp(n,k); [o]d(j,k));',
'',
'
loop(n,k) %{ double tmp0 = 0;
loop(m) %{ tmp0 += $b() * $c(); %}
$tmp() = tmp0;
%}
loop(j,k) %{ double tmp1 = 0;
loop(n) %{ tmp1 += $a() * $tmp(); %}
$d() = tmp1;
%}',<<'EOD');
=for ref
Efficient Triple matrix product a*b*c
Efficiency comes from by using the temporary tmp. This operation only scales as
N**3 whereas threading using inner2 would scale as N**4.
The reason for having this routine is that you do not need to
have the same thread-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
EOD
=item minimum_ind(a(n),int [o]c()), maximum_ind(a(n),int [o]c())
These functions work like the previous except that they
return the index of the maximum element
=item minimum_n_ind(a(n),int [o]c(m)), maximum_n_ind(a(n),int [o]c(m))
These functions work like the previous except that they
return the indices of the I<m> maximum elements.
=cut
for $which (['minimum','<'],
['maximum','>']) {
defpdl(
$which->[0],
'a(n); [o]c();','',
'$GENERIC() cur;
loop(n) %{
if(!n || $a() '.$which->[1].' cur || IsNaN(cur)) {cur = $a();}
%}
$c() = cur;
', projectdocs($which->[0],$which->[0])
);
defpdl(
$which->[0]."_ind",
'a(n); int[o]c();','',
'$GENERIC() cur; int curind;
loop(n) %{
if(!n || $a() '.$which->[1].' cur || IsNaN(cur))
{cur = $a(); curind = n;}
%}
$c() = curind;
',"Like $which->[0] but returns the index rather than the value"
);
defpdl(
$which->[0]."_n_ind",
'a(n); int[o]c(m);','',
'$GENERIC() cur; int curind;
if($SIZE(m) > $SIZE(n)) $CROAK("n_ind: m_size > n_size");
loop(m) %{
loop(n) %{
int nm; int flag=0;
for(nm=0; nm<m; nm++) {
if($c(m=>nm) == n) {flag=1; break;}
}
if(!flag &&
(n<=m || $a() '.$which->[1].' cur || IsNaN(cur)))
{cur = $a(); curind = n;}
%}
$c() = curind;
%}
',"Returns the index of C<m> $which->[0] elements"
);
}
pp_addpm(<<'EOD'
=cut
=head2 minmaximum
=for ref
Find minimum and maximum and their indices for a given piddle;
=for usage
perldl> $a=pdl [[-2,3,4],[1,0,3]]
perldl> ($min, $max, $min_ind, $max_ind)=minmaximum($a)
perldl> p $min, $max, $min_ind, $max_ind
[-2 0] [4 3] [0 1] [2 2]
See also minmax, which clumps the piddle together.
=cut
EOD
);
pp_def( 'minmaximum',
Pars => 'a(n); [o]cmin(); [o] cmax(); int [o]cmin_ind(); int [o]cmax_ind();',
Code => '$GENERIC() curmin, curmax;
int curmin_ind, curmax_ind;
loop(n) %{
if (!n || ($a() < curmin) || IsNaN(curmin)) {curmin = $a(); curmin_ind = n;};
if (!n || ($a() > curmax) || IsNaN(curmax)) {curmax = $a(); curmax_ind = n;};
%}
$cmin() = curmin;
$cmax() = curmax;
$cmin_ind() = curmin_ind;
$cmax_ind() = curmax_ind;'
);
for (['hclip','>'],['lclip','<']) {
pp_def($_->[0],
Pars => 'a(); b(); [o] c()',
Code => '$c() = ($a() '.$_->[1].' $b()) ? $b() : $a();',
Doc => 'clip $a by $b ($b is '.($_->[0] eq 'hclip' ? 'upper' :
'lower').' bound)',
PMCode=><<"EOD",
sub PDL::$_->[0] {
my (\$a,\$b) = \@_;
my \$c;
if (\$a->is_inplace) {
\$a->set_inplace(0); \$c = \$a;
} elsif (\$#_ > 1) {\$c=\$_[2]} else {\$c=PDL->nullcreate(\$a)}
&PDL::_$_->[0]_int(\$a,\$b,\$c);
return \$c;
}
EOD
);
}
pp_add_exported('', clip);
pp_addpm(<<'EOD');
=head2 clip
=for ref
Clip a piddle by (optional) upper or lower bounds.
=for usage
$b = $a->clip(0,3);
$c = $a->clip(undef, $x);
=cut
*clip = \&PDL::clip;
sub PDL::clip {
my($a, $b, $c) = @_;
my $d; if($a->is_inplace) {$a->set_inplace(0); $d = $a}
elsif($#_ > 2) {$d=$_[3]} else {$d = PDL->nullcreate($a)}
if(defined $b) {
&PDL::_lclip_int($a,$b,$d);
if(defined $c) {
&PDL::_hclip_int($d,$c,$d);
}
} elsif(defined $c) {
&PDL::_hclip_int($a,$c,$d);
}
return $d;
}
EOD
defpdl(
'wtstat',
'a(n); wt(n); avg(); [o]b();',
'int deg',
'double wtsum = 0;
double statsum=0;
loop(n) %{
register double tmp; register int i;
wtsum += $wt();
tmp=1; for(i=0; i<$COMP(deg); i++) tmp*=$a();
statsum += $wt() * (tmp - $avg()); %}
$b() = statsum / wtsum;
',<<'EOD');
=head2 wtstat
=for ref
Weighted statistical moment of given degree
This calculates a weighted statistic over the vector a.
The formula is
b() = (sum_i wt_i * (a_i ** degree - avg)) / (sum_i wt_i)
=cut
EOD
pp_addpm(<<'EOD');
=head2 random
=for ref
Constructor which returns piddle of random numbers
=for usage
$a = random([type], $nx, $ny, $nz,...);
$a = random $b;
etc. (see 'zeroes')
This is the uniform distribution between 0 and 1 (assumedly
excluding 1 itself). The arguments are the same as C<zeroes>
(q.v.) - i.e. one can specify dimensions, types or give
a template.
=head2 randsym
=for ref
Constructor which returns piddle of random numbers
=for usage
$a = randsym([type], $nx, $ny, $nz,...);
$a = randsym $b;
etc. (see 'zeroes')
This is the uniform distribution between 0 and 1 (excluding both 0 and
1, cf C<random>). The arguments are the same as C<zeroes> (q.v.) -
i.e. one can specify dimensions, types or give a template.
=cut
EOD
pp_def(
'random',
Pars=>'a();',
PMFunc => '',
Code =>
'$a() = ((double)rand()) / (RAND_MAX+1.0);',
Doc=>undef,
PMCode=><<'EOD',
sub random { ref($_[0]) && ref($_[0]) ne 'PDL::Type' ? $_[0]->random : PDL->random(@_) }
sub PDL::random {
my $class = shift;
my $x = scalar(@_)? $class->new_from_specification(@_) : $class->new_or_inplace;
&PDL::_random_int($x);
return $x;
}
EOD
);
pp_def(
'randsym',
Pars=>'a();',
PMFunc => '',
Code =>
'$a() = (0.5+(double)rand()) / (RAND_MAX+1.0);',
Doc=>undef,
PMCode=><<'EOD',
sub randsym { ref($_[0]) && ref($_[0]) ne 'PDL::Type' ? $_[0]->randsym : PDL->randsym(@_) }
sub PDL::randsym {
my $class = shift;
my $x = scalar(@_)? $class->new_from_specification(@_) : $class->new_or_inplace;
&PDL::_randsym_int($x);
return $x;
}
EOD
);
pp_addpm(<<'EOD');
=head2 grandom
=for ref
Constructor which returns piddle of Gaussian random numbers
=for usage
$a = grandom([type], $nx, $ny, $nz,...);
$a = grandom $b;
etc. See 'zeroes'
This is generated using the math library routine `ndtri'.
Mean = 0, Stddev = 1
=cut
sub grandom { ref($_[0]) && ref($_[0]) ne 'PDL::Type' ? $_[0]->grandom : PDL->grandom(@_) }
sub PDL::grandom {
my $class = shift;
my $x = scalar(@_)? $class->new_from_specification(@_) : $class->new_or_inplace;
use PDL::Math 'ndtri';
$x .= ndtri(randsym($x));
return $x;
}
EOD
pp_add_exported('','grandom');
defpdl(
'assgn',
'a(); [o]b();',
'',
'$b() = $a();',
'Plain numerical assignment. This is used to implement the ".=" operator'
);
# The last x is ignored...
pp_def('vsearch',
Pars => 'i(); x(n); int [o]ip()',
GenericTypes => [F,D], # too restrictive ?
Code => 'int carp=0;
threadloop %{
long n1 = $SIZE(n)-1;
long jl=-1, jh=n1, m;
int up = ($x(n => n1) > $x(n => 0));
$GENERIC() d;
while (jh-jl > 1) /* binary search */
{
m = (jh+jl) >> 1;
if ($i() > $x(n => m) == up)
jl = m;
else
jh = m;
}
if (jl == -1) {
jh = 0;
} else if (jl == n1) {
if ($i() != $x(n => n1)) carp = 1;
jh = n1;
} else {
jh = jl+1;
}
$ip() = jh;
%}
if (carp) warn("some values had to be extrapolated");
', Doc=><<'EOD');
=for ref
routine for searching 1D values i.e. step-function interpolation.
=for usage
$inds = vsearch($vals, $xs);
Returns for each value of $val the index of the least larger member
of $xs (which need to be in increasing order). If the value is larger
than any member of $xs, the index to the last element of $xs is returned.
=for example
This function is useful e.g. when you have a list of probabilities
for events and want to generate indices to events:
$a = pdl(.01,.86,.93,1); # Barnsley IFS probabilities cumulatively
$b = random 20;
$c = vsearch($b, $a); # Now, $c will have the appropriate distr.
It is possible to use the C<cumusumover> function to obtain
cumulative probabilities from absolute probabilities.
EOD
pp_def('interpol',
Pars => 'i(); x(n); y(n); [o] ip()',
GenericTypes => [F,D], # too restrictive ?
Code => 'int carp=0;
threadloop %{
long n1 = $SIZE(n)-1;
long jl=-1, jh=n1, m;
int up = ($x(n => n1) > $x(n => 0));
$GENERIC() d;
while (jh-jl > 1) /* binary search */
{
m = (jh+jl) >> 1;
if ($i() > $x(n => m) == up)
jl = m;
else
jh = m;
}
if (jl == -1) {
if ($i() != $x(n => 0)) carp = 1;
jl = 0;
} else if (jl == n1) {
if ($i() != $x(n => n1)) carp = 1;
jl = n1-1;
}
jh = jl+1;
if ((d = $x(n => jh)-$x(n => jl)) == 0)
barf("identical abscissas");
d = ($x(n => jh)-$i())/d;
$ip() = d*$y(n => jl) + (1-d)*$y(n => jh);
%}
if (carp) warn("some values had to be extrapolated");
', Doc=><<'EOD');
=for ref
routine for 1D linear interpolation
=for usage
$interpolated_values = interpol($interpol_at, $ordered_abscissas, $yvalues)
'interpol' uses a binary search to find the suspects, er...,
interpolation indices and therefore abscissas have to be strictly
ordered (increasing or decreasing). For interpolation at lots of
closely spaced abscissas an approach that uses the last index found as
a start for the next search can be faster (compare Numerical Recipes
'hunt' routine). Feel free to implement that on top of the binary
search if you like. For out of bounds values it just does a linear
extrapolation and issues a warning upon completion.
=cut
EOD
pp_add_exported("", one2nd);
pp_addpm(<<'EOD');
=head2 one2nd
=for ref
Converts a one dimensional index piddle to a set of ND coordinates
=for usage
@coords=one2nd($a, $indices)
returns an array of piddles containing the ND indexes corresponding to
the one dimensional list indices. The indices are assumed to correspond
to array $a clumped using clump(-1). This routine is used in whichND,
but is useful on its own occasionally.
=for example
perldl> $a=pdl [[[1,2],[-1,1]], [[0,-3],[3,2]]]; $c=$a->clump(-1)
perldl> $maxind=maximum_ind($c); p $maxind;
6
perldl> print one2nd($a, maximum_ind($c))
0 1 1
perldl> p $a->at(0,1,1)
3
=cut
*one2nd = \&PDL::one2nd;
sub PDL::one2nd {
barf "Usage: one2nd $array $indices\n" if $#_ != 1;
my ($a, $ind)=@_;
my @dimension=$a->dims;
my(@index);
my $count=0;
foreach (@dimension) {
$index[$count++]=$ind % $_;
$ind=long($ind/$_);
}
return @index;
}
EOD
pp_addpm(<<'EOD'
=head2 which
=for ref
Returns piddle of indices of non-zero values.
=for usage
$i = which($mask);
returns a pdl with indices for all those elements that are
nonzero in the mask. Note that mask really has to be 1-D (use clump(-1)
if you need to work with ND-images)
If you want to return both the indices of non-zero values and the
complement, use the function which_both.
=for example
perldl> $x = sequence(10); p $x
[0 1 2 3 4 5 6 7 8 9]
perldl> $indx = which($x>6); p $indx
[7 8 9]
=cut
=head2 which_both
=for ref
Returns piddle of indices of non-zero values and their complement
=for usage
($i, $c_i) = which_both($mask);
This works just as which, but the complement of $i will be in $c_i.
=for example
perldl> $x = sequence(10); p $x
[0 1 2 3 4 5 6 7 8 9]
perldl> ($small, $big) = which_both ($x >= 5); p "$small\n $big"
[5 6 7 8 9]
[0 1 2 3 4]
=cut
EOD
);
for ({Name=>'which',
Pars => 'mask(n); int [o] inds(m);',
Variables => 'int dm=0;',
Elseclause => "",
Autosize => '$SIZE(m) = sum;'},
{Name => 'which_both',
Pars => 'mask(n); int [o] inds(m); int [o]notinds(q)',
Variables => 'int dm=0; int dm2=0;',
Elseclause => "else { \n \$notinds(q => dm2)=n; \n dm2++;\n }",
Autosize => '$SIZE(m) = sum;'."\n".' $SIZE(q) = dpdl->dims[0]-sum;'})
{
pp_def($_->{Name},
Pars => $_->{Pars},
Code => $_->{Variables} .
'loop(n) %{
if ($mask()) {
$inds(m => dm) = n;
dm++;
}'.$_->{Elseclause} . "\n".
' %}',
# the next one is currently a dirty hack
# this will probably break once dataflow is enabled again
# *unless* we have made sure that mask is physical by now!!!
RedoDimsCode => '
PDL_Long sum = 0;
/* not sure if this is necessary */
pdl * dpdl = $PDL(mask);
$GENERIC() *m_datap = (($GENERIC() *)(PDL_REPRP(dpdl)));
PDL_Long inc = PDL_REPRINC(dpdl,0);
PDL_Long offs = PDL_REPROFFS(dpdl);
int i;
if (dpdl->ndims != 1)
barf("dimflag currently works only with 1D pdls");
for (i=0; i<dpdl->dims[0]; i++) {
if ( *(m_datap+inc*i+offs)) sum++;
}
'.$_->{Autosize} . '
/* printf("RedoDimsCode: setting dim m to %ld\n",sum); */'
);
}
pp_addpm(<<'EOD'
=head2 where
=for ref
Returns indices to non-zero values or those values from another piddle.
=for usage
$i = $x->where($x+5 > 0); # $i contains elements of $x
# where mask ($x+5 > 0) is 1
Note: $i is always 1-D, even if $x is >1-D. The first argument
(the values) and the second argument (the mask) currently have to have
the same initial dimensions (or horrible things happen).
It is also possible to use the same mask for several piddles with
the same call:
($i,$j,$k) = where($x,$y,$z, $x+5>0);
There is also the following syntax, retained only for compatibility
with PDL versions <1.99.
This use is deprecated, and will be removed
in the future. Use C<which> instead.
$i = where($x > 0); # indices to $x, equivalent to 'which()'
Note: the mask has to be 1-D. See the documentation for C<which>
=cut
sub PDL::where {
if($#_ == 0) {
warn "WARNING: one argument form of where() is now deprecated - use which()\n";
return $_[0]->which();
} elsif($#_ == 1) {
my($data,$mask) = @_;
$data = $_[0]->clump(-1) if $_[0]->getndims>1;
$mask = $_[1]->clump(-1) if $_[0]->getndims>1;
return $data->index($mask->which());
} else {
if($_[-1]->getndims > 1) {
my $mask = $_[-1]->clump(-1)->which;
return map {$_->clump(-1)->index($mask)}
@_[0..$#_-1];
} else {
my $mask = $_[-1]->which;
return map {$_->index($mask)} @_[0..$#_-1];
}
}
}
*where = \&PDL::where;
EOD
);
pp_add_exported("", where);
pp_def('append',
Pars => 'a(n); b(m); [o] c(mn)',
# note that ideally we want to say '$SIZE(mn) = $SIZE(m)+$SIZE(n);'
# but that requires placing RedoDimsParsedCode *after* assignment of
# childdims to $SIZE(XXX)!!! XXXXXmake that workXXXXX
RedoDimsCode => '
pdl * dpdla = $PDL(a);
pdl * dpdlb = $PDL(b);
$SIZE(mn) = dpdla->dims[0] + dpdlb->dims[0];',
Code => 'register PDL_Long mnp;
PDL_Long ns = $SIZE(n);
threadloop %{
loop(n) %{ $c(mn => n) = $a(); %}
loop(m) %{ mnp = m+ns; $c(mn => mnp) = $b(); %}
%}',
Doc => << 'EOD',
=for ref
append two piddles by concantening along their respective first dimensions
=for example
$a = ones(2,4,7);
$b = sequence 5;
$c = $a->append($b); # size of $c is now (7,4,7) (a jumbo-piddle ;)
C<append> appends two piddles along their first dims. Rest of the dimensions
must be compatible in the threading sense. Resulting size of first dim is
sum of sizes of the two argument piddles' first dims.
EOD
);
for({Name => 'histogram',
WeightPar => '',
HistType => 'int+',
HistOp => '++',
Doc1 => "",
Doc2 => "",
Doc3 => "number of\n",
Doc4 => "\nUse C<hist()> instead for a high-level interface.\n",
Doc5 => "histogram(pdl(1,1,2),1,0,3)\n [0 2 1]"},
{Name => 'whistogram',
WeightPar => 'float+ wt(n);',
HistType => 'float+',
HistOp => '+= $wt()',
Doc1 => " from weighted data",
Doc2 => "\$weights, ",
Doc3 => "sum of the values in \$weights\nthat correspond to ",
Doc4 => "",
Doc5 => "whistogram(pdl(1,1,2), pdl(0.1,0.1,0.5), 1, 0, 4)\n [0 0.2 0.5 0]"})
{
pp_def($_->{Name},
Pars => 'in(n); '.$_->{WeightPar}.$_->{HistType}. '[o] hist(m)',
# set outdim by Par!
OtherPars => 'double step; double min; int msize => m',
Code => 'register int j;
register int maxj = $SIZE(m)-1;
register double min = $COMP(min);
register double step = $COMP(step);
threadloop %{
loop(m) %{ $hist() = 0; %}
%}
threadloop %{
loop(n) %{
j = (int) (($in()-min)/step);
if (j<0) j=0;
if (j > maxj) j = maxj;
($hist(m => j))'.$_->{HistOp}.';
%}
%}
',
Doc=><<"EOD");
=for ref
Calculates a histogram$_->{Doc1} for given stepsize and minimum.
=for usage
\$h = $_->{Name}(\$data, $_->{Doc2}\$step, \$min, \$numbins);
\$hist = zeroes \$numbins; # Put histogram in existing piddle.
$_->{Name}(\$data, $_->{Doc2}\$hist, \$step, \$min, \$numbins);
The histogram will contain \$numbins bins starting from \$min, each
\$step wide. The value in each bin is the $_->{Doc3}values in \$data that lie within the bin limits.
Data below the lower limit is put in the first bin, and data above the
upper limit is put in the last bin.
The output is reset in a different threadloop so that you
can take a histogram of \$a(10,12) into \$b(15) and get the result
you want.
$_->{Doc4}
=for example
perldl> p $_->{Doc5}
=cut
EOD
}
for({Name => 'histogram2d',
WeightPar => '',
HistType => 'int+',
HistOp => '++',
Doc1 => "",
Doc2 => "",
Doc3 => "number of\n",
Doc5 => "histogram2d(pdl(1,1,1,2,2),pdl(2,1,1,1,1),1,0,3,1,0,3)
[
[0 0 0]
[0 2 2]
[0 1 0]
]
"},
{Name => 'whistogram2d',
WeightPar => 'float+ wt(n);',
HistType => 'float+',
HistOp => '+= $wt()',
Doc1 => " from weighted data",
Doc2 => " \$weights,",
Doc3 => "sum of the values in\n\$weights that correspond to ",
Doc5 => "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)
[
[ 0 0 0]
[ 0 0.5 0.9]
[ 0 0.1 0]
]
"})
{
pp_def($_->{Name},
Pars => 'ina(n); inb(n); '.$_->{WeightPar}.$_->{HistType}. '[o] hist(ma,mb)',
# set outdim by Par!
OtherPars => 'double stepa; double mina; int masize => ma;
double stepb; double minb; int mbsize => mb;',
Code => 'register int ja,jb;
register int maxja = $SIZE(ma)-1;
register int maxjb = $SIZE(mb)-1;
register double mina = $COMP(mina);
register double minb = $COMP(minb);
register double stepa = $COMP(stepa);
register double stepb = $COMP(stepb);
threadloop %{
loop(ma,mb) %{ $hist() = 0; %}
%}
threadloop %{
loop(n) %{
ja = (int) (($ina()-mina)/stepa);
jb = (int) (($inb()-minb)/stepb);
if (ja<0) ja=0;
if (ja > maxja) ja = maxja;
if (jb<0) jb=0;
if (jb > maxjb) jb = maxjb;
($hist(ma => ja,mb => jb))'.$_->{HistOp}.';
%}
%}
',
Doc=><<"EOD");
=for ref
Calculates a 2d histogram$_->{Doc1}.
=for usage
\$h = $_->{Name}(\$datax, \$datay,$_->{Doc2}
\$stepx, \$minx, \$nbinx, \$stepy, \$miny, \$nbiny);
\$hist = zeroes \$nbinx, \$nbiny; # Put histogram in existing piddle.
$_->{Name}(\$datax, \$datay,$_->{Doc2} \$hist,
\$stepx, \$minx, \$nbinx, \$stepy, \$miny, \$nbiny);
The histogram will contain \$nbinx x \$nbiny bins, with the lower
limits of the first one at (\$minx, \$miny), and with bin size
(\$stepx, \$stepy). The value in each bin is the $_->{Doc3}values in \$datax and \$datay that lie within the bin limits.
Data below the lower limit is put in the first bin, and data above the
upper limit is put in the last bin.
=for example
perldl> p $_->{Doc5}
=cut
EOD
}
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 $a, $b
the inner product $c*$a and $c*$b will be zero, i.e. $c is
orthogonal to $a and $b
=cut
EOD
Pars => 'a(tri=3); b(tri); [o] c(tri)',
Code => crassgn(0,1,2)."\n".
crassgn(1,2,0)."\n".
crassgn(2,0,1),
);
pp_def('norm',
Pars => 'vec(n); [o] norm(n)',
Doc => 'Normalises a vector to unit Euclidean length',
Code => 'double sum=0;
loop(n) %{ sum += $vec()*$vec(); %}
if (sum > 0) {
sum = sqrt(sum);
loop(n) %{ $norm() = $vec()/sum; %}
} else {
loop(n) %{ $norm() = $vec(); %}
}',
);
pp_add_exported('','stats');
pp_addpm(<<'EOD');
=head2 stats
=for ref
Calculates useful statistics on a piddle
=for usage
($mean,$rms,$median,$min,$max) = stats($piddle,[$weights]);
This utility calculates all the most useful
quantities in one call.
B<Note:> The RMS value that this function returns in the RMS
deviation from the mean, also known as the population standard-
deviation.
=cut
*stats = \&PDL::stats;
sub PDL::stats {
barf('Usage: ($mean,[$rms]) = stats($data,[$weights])') if $#_>1;
my ($data,$weights) = @_;
my ($mean,$rms);
if ($#_==0) {
$mean = ($data->sum)/($data->nelem);
$rms = sqrt( ((($data-$mean)**2 )->sum) / ($data->nelem) );
}
else {
$mean = (($weights*$data)->sum) / (($weights)->sum);
$rms = sqrt( ( ( $weights*(($data-$mean)**2) )->sum ) / ($weights->sum) );
}
my ($median,$min,$max) = ($data->median,$data->min,$data->max);
print "Mean = $mean, RMS = $rms, Median = $median\n".
"Min = $min, Max = $max\n" if $PDL::verbose;
return $mean unless wantarray;
return ($mean,$rms,$median,$min,$max);
}
EOD
pp_addpm(<<'EOD'
=head2 whichND
=for ref
Returns the coordinates for non-zero values
=for usage
@coords=whichND($mask);
returns an array of piddles containing the coordinates of the elements
that are non-zero in $mask.
=for example
perldl> $a=sequence(10,10,3,4)
perldl> ($x, $y, $z, $w)=whichND($a == 203); p $x, $y, $z, $w
[3] [0] [2] [0]
perldl> print $a->at(list(cat($x,$y,$z,$w)))
203
=cut
*whichND = \&PDL::whichND;
sub PDL::whichND {
my $mask = shift;
my $ind=($mask->clump(-1))->which;
return $mask->one2nd($ind);
}
EOD
);
pp_add_exported("", whichND);
pp_def('fibonacci',
Pars => '[o]x(n);',
Doc=>'Constructor - a vector with Fibonacci\'s sequence',
PMFunc=>'',
PMCode=><<'EOD',
sub fibonacci { ref($_[0]) && ref($_[0]) ne 'PDL::Type' ? $_[0]->fibonacci : PDL->fibonacci(@_) }
sub PDL::fibonacci{
my $class = shift;
my $x = scalar(@_)? $class->new_from_specification(@_) : $class->new_or_inplace;
&PDL::_fibonacci_int($x->clump(-1));
return $x;
}
EOD
Code => '
PDL_Long i=0;
$GENERIC() x1, x2;
x1 = 1; x2 = 0;
loop(n) %{
$x() = x1 + x2;
if (i++>0) {
x2 = x1;
x1 = $x();
}
%}
');
pp_def('indadd',
Pars => 'a(); int ind(); [o] sum(m)',
Code => 'register int foo = $ind();
if(foo<0 || foo>=$SIZE(m))
{barf("PDL::indadd: invalid index");}
$sum(m => foo) += $a();',
Doc=>'
=for ref
Threaded Index Add: Add C<a> to the C<ind> element of C<sum>, i.e:
sum(ind) += a
=for example
Simple Example:
$a = 2;
$ind = 3;
$sum = zeroes(10);
indadd($a,$ind, $sum);
print $sum
#Result: ( 2 added to element 3 of $sum)
# [0 0 0 2 0 0 0 0 0 0]
Threaded Example:
$a = pdl( 1,2,3);
$ind = pdl( 1,4,6);
$sum = zeroes(10);
indadd($a,$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
');
pp_addpm({At=>Bot},<<'EOD');
=head1 AUTHOR
Copyright (C) Tuomas J. Lukka 1997 (lukka@husc.harvard.edu). Contributions
by Christian Soeller (c.soeller@auckland.ac.nz) and Karl Glazebrook
(kgb@aaoepp.aao.gov.au).
All rights reserved. There is no warranty. You are allowed
to redistribute this software / documentation under certain
conditions. For details, see the file COPYING in the PDL
distribution. If this file is separated from the PDL distribution,
the copyright notice should be included in the file.
=cut
EOD
pp_done();
|