File: primitive.pd

package info (click to toggle)
pdl 1:2.019-5
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 12,276 kB
  • sloc: perl: 47,799; fortran: 13,113; ansic: 9,365; sh: 41; makefile: 38; sed: 6
file content (3919 lines) | stat: -rw-r--r-- 97,482 bytes parent folder | download
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
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
use strict;

# check for bad value support
use PDL::Config;
my $bvalflag = $PDL::Config{WITH_BADVAL} || 0;

pp_addhdr(<<'EOD');

#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|PDL::Indexing> for how to use indices creatively.
For explanation of the signature format, see L<PDL::PP|PDL::PP>.

=head1 SYNOPSIS

 # Pulls in PDL::Primitive, among other modules.
 use PDL;

 # Only pull in PDL::Primitive:
 use PDL::Primitive;

=cut

EOD

=head1 FUNCTIONS

=cut

################################################################
#  a whole bunch of quite basic functions for inner, outer
#  and matrix products (operations that are not normally
#  available via operator overloading)
################################################################

=head2 inner

=for sig

  Signature: (a(n); b(n); [o]c())

=cut

pp_def(
       'inner',
       HandleBad => 1,
       Pars => 'a(n); b(n); [o]c();',
       Code =>
       'double tmp = 0;
        loop(n) %{ tmp += $a() * $b(); %}
        $c() = tmp;',
       BadCode =>
       'double tmp = 0;
        int badflag = 0;
        loop(n) %{
           if ( $ISGOOD(a()) && $ISGOOD(b()) ) { tmp += $a() * $b(); } else { badflag = 1; }
        %}
        if ( badflag ) { $SETBAD(c()); $PDLSTATESETBAD(c); }
        else        { $c() = tmp;  }',
       CopyBadStatusCode => '',
       Doc => '

=for ref

Inner product over one dimension

 c = sum_i a_i * b_i

=cut

',
       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.

=cut

',
       ); # pp_def( inner )

=head2 outer

=for sig

  Signature: (a(n); b(m); [o]c(n,m))

=cut

pp_def(
       'outer',
       HandleBad => 1,
       Pars => 'a(n); b(m); [o]c(n,m);',
       Code =>
       'loop(n,m) %{
          $c() = $a() * $b();
        %}',
       BadCode =>
       'loop(n,m) %{
          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 threading over the "C<*>"
operator but this function is provided for convenience.

=cut

'); # 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.

Threading 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 thread over either of those dims.

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|/matmult> method.

=cut

EOD

pp_add_exported('', 'matmult');

pp_def('matmult',
	HandleBad=>0,
	Pars => 'a(t,h); b(w,t); [o]c(w,h);',
	PMCode => <<'EOPM',
sub PDL::matmult {
    my ($a,$b,$c) = @_;

    $b = pdl($b) unless eval { $b->isa('PDL') };
    $c = PDL->null unless eval { $c->isa('PDL') };

    while($a->getndims < 2) {$a = $a->dummy(-1)}
    while($b->getndims < 2) {$b = $b->dummy(-1)}

    return ($c .= $a * $b) if( ($a->dim(0)==1 && $a->dim(1)==1) ||
    	       	       	       ($b->dim(0)==1 && $b->dim(1)==1) );
    if($b->dim(1) != $a->dim(0)) {
        barf(sprintf("Dim mismatch in matmult of [%dx%d] x [%dx%d]: %d != %d",$a->dim(0),$a->dim(1),$b->dim(0),$b->dim(1),$a->dim(0),$b->dim(1)));
    }
    PDL::_matmult_int($a,$b,$c);
    $c;
}
EOPM
	Code => <<'EOC',
	PDL_Indx ih, iw, it, ow, oh, ot, wlim, hlim, tlim;
        $GENERIC() *ad, *bd, *cd;
        PDL_Indx atdi, btdi;
	PDL_Indx resh, resw, rest;
	PDL_Indx tsiz = 64;

	// Zero the output
	loop(w) %{
		loop(h) %{
			$c() = 0;
		%}
	%}

	// Make sure we're physical
	// (Not needed if we don't need dimincs, see below)
	// PDL->make_physdims($PDL(a));
	// PDL->make_physdims($PDL(b));

        // Cache the dimincs to avoid constant lookups
	// These two lines are what I wanted, but they break sometimes (dimincs not set right despite calling physdims?)
	// I deleted them in favor of explicit offset calculation, which appears more robust.
	//	atdi = $PDL(a)->dimincs[0];
	//	btdi = $PDL(b)->dimincs[1];
	atdi = &($a(t=>1, h=>0)) - &($a(t=>0,h=>0));
	btdi = &($b(t=>1, w=>0)) - &($b(t=>0,w=>0));


	// Loop over tiles
	for(   oh=0;   oh < $SIZE(h);   oh += tsiz   ) {
	   hlim = ( oh + tsiz > $SIZE(h) )  ?  $SIZE(h)  :  oh + tsiz;

	   for(   ow=0;   ow < $SIZE(w);   ow += tsiz   ) {
	      wlim = ( ow + tsiz > $SIZE(w) )  ?  $SIZE(w)  :  ow + tsiz;

	      for(   ot=0;   ot < $SIZE(t);  ot += tsiz   ) {
	         tlim = (ot + tsiz > $SIZE(t) )  ?  $SIZE(t)  :  ot + tsiz;


	         for(  ih=oh; ih<hlim; ih++  ) {
		    for(  iw=ow; iw<wlim; iw++  ) {
		       $GENERIC() cc;

		       // Cache data pointers before 't' run through tile
		       ad = &($a(t=>ot, h=>ih));
		       bd = &($b(w=>iw, t=>ot));

		       // Cache the accumulated value for the output
		       cc = $c(w=>iw, h=>ih);

		       // 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 $a x $b is equivalent to the
threading expression

    $a->dummy(1)->inner($b->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|/x>, a description of the overloaded 'x' operator

EOD
	);

=head2 innerwt

=for sig

  Signature: (a(n); b(n); c(n); [o]d())

=cut

pp_def(
       'innerwt',
       HandleBad => 1,
       Pars => 'a(n); b(n); c(n); [o]d();',
       Code =>
       'double tmp = 0;
	loop(n) %{
           tmp += $a() * $b() * $c();
        %}
	$d() = tmp;',
       BadCode =>
       'double tmp = 0;
        int flag = 0;

	loop(n) %{
           if ( $ISGOOD(a()) && $ISGOOD(b()) && $ISGOOD(c()) ) {
              tmp += $a() * $b() * $c();
              flag = 1;
           }
        %}
        if ( flag ) { $d() = tmp; }
        else        { $SETBAD(d()); }',
       Doc => '

=for ref

Weighted (i.e. triple) inner product

 d = sum_i a(i) b(i) c(i)

=cut

'
       );

=head2 inner2

=for sig

  Signature: (a(n); b(n,m); c(m); [o]d())

=cut

pp_def(
       'inner2',
       HandleBad => 1,
       Pars => 'a(n); b(n,m); c(m); [o]d();',
       Code =>
       'double tmp=0;
	loop(n,m) %{
           tmp += $a() * $b() * $c();
        %}
	$d() = tmp;',
       BadCode =>
       'double tmp = 0;
        int flag = 0;
	loop(n,m) %{
           if ( $ISGOOD(a()) && $ISGOOD(b()) && $ISGOOD(c()) ) {
              tmp += $a() * $b() * $c();
              flag = 1;
           }
        %}
        if ( flag ) { $d() = tmp; }
        else        { $SETBAD(d()); }',
       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 thread over C<a> and C<c> since that would be
very wasteful. Instead, you should use a temporary for C<b*c>.

=cut

'
       );

=head2 inner2d

=for sig

  Signature: (a(n,m); b(n,m); [o]c())

=cut

pp_def(
       'inner2d',
       HandleBad => 1,
       Pars => 'a(n,m); b(n,m); [o]c();',
       Code =>
       'double tmp=0;
	loop(n,m) %{
           tmp += $a() * $b();
        %}
	$c() = tmp;',
       BadCode =>
       'double tmp = 0;
        int flag = 0;
	loop(n,m) %{
           if ( $ISGOOD(a()) && $ISGOOD(b()) ) {
              tmp += $a() * $b();
              flag = 1;
           }
        %}
        if ( flag ) { $c() = tmp; }
        else        { $SETBAD(c()); }',
       Doc => '

=for ref

Inner product over 2 dimensions.

Equivalent to

 $c = inner($a->clump(2), $b->clump(2))

=cut

'
       );

=head2 inner2t

=for sig

  Signature: (a(j,n); b(n,m); c(m,k); [t]tmp(n,k); [o]d(j,k)))

=cut

pp_def(
       'inner2t',
       HandleBad => 1,
       Pars => 'a(j,n); b(n,m); c(m,k); [t]tmp(n,k); [o]d(j,k));',
       Code =>
       '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;
	%}',
       BadCode =>
       'loop(n,k) %{
           double tmp0 = 0;
           int flag = 0;
	   loop(m) %{
              if ( $ISGOOD(b()) && $ISGOOD(c()) ) {
                 tmp0 += $b() * $c();
                 flag = 1;
              }
           %}
           if ( flag ) { $tmp() = tmp0; }
           else        { $SETBAD(tmp()); }
	%}
	loop(j,k) %{
           double tmp1 = 0;
           int flag = 0;
	   loop(n) %{
              if ( $ISGOOD(a()) && $ISGOOD(tmp()) ) {
                 tmp1 += $a() * $tmp();
                 flag = 1;
              }
           %}
           if ( flag ) { $d() = tmp1; }
           else        { $SETBAD(d()); }
	%}',
       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 threading using L<inner2|/inner2> would scale
as C<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

'
       ); # 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]);"
}

=head2 crossp

=for sig

  Signature: (a(tri=3); b(tri); [o] c(tri))

=cut

pp_def('crossp',
       Doc => <<'EOD',

=for ref

Cross product of two 3D vectors

After

=for example

 $c = crossp $a, $b

the inner product C<$c*$a> and C<$c*$b> will be zero, i.e. C<$c> is
orthogonal to C<$a> and C<$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),
       );

=head2 norm

=for sig

  Signature: (vec(n); [o] norm(n))

Normalises a vector to unit Euclidean length

=cut

pp_def('norm',
       HandleBad => 1,
       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(); %}
	}',
       BadCode =>
       'double sum=0;
        int flag = 0;
	loop(n) %{
           if ( $ISGOOD(vec()) ) {
              sum += $vec()*$vec();
              flag = 1;
           }
        %}
        if ( flag ) {
	   if (sum > 0) {
	      sum = sqrt(sum);
	      loop(n) %{
                 if ( $ISBAD(vec()) ) { $SETBAD(norm()); }
                 else                 { $norm() = $vec()/sum; }
              %}
	   } else {
	      loop(n) %{
                 if ( $ISBAD(vec()) ) { $SETBAD(norm()); }
                 else                 { $norm() = $vec(); }
              %}
           }
        } 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

=head2 indadd

=for sig

  Signature: (a(); indx ind(); [o] sum(m))

=cut

pp_def(
    'indadd',
    HandleBad => 1,
    Pars => 'a(); indx ind(); [o] sum(m)',
    Code =>
    'register PDL_Indx foo = $ind();
     if( foo<0 || foo>=$SIZE(m) ) {
       barf("PDL::indadd: invalid index");
     }
     $sum(m => foo) += $a();',
    BadCode =>
    'register PDL_Indx foo = $ind();
     if( $ISBADVAR(foo,ind) || foo<0 || foo>=$SIZE(m) ) {
       barf("PDL::indadd: invalid index");
     }
     if ( $ISBAD(a()) ) { $SETBAD(sum(m => foo)); }
     else               { $sum(m => foo) += $a(); }',
    BadDoc => '

=for bad

The routine barfs if any of the indices are bad.

=cut

',
    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

');

=head2 conv1d

=for sig

  Signature: (a(m); kern(p); [o]b(m); int reflect)

=cut

# 1D convolution
# useful for threaded 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 piddle
C<$a> of size C<$M>, and a kernel piddle 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.

  $b = $a->mv(2,0)->conv1d($kernel)->mv(0,2); # along third dim

This function is useful for threaded 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);',
        OtherPars => 'int reflect;',
        HandleBad => 0,
        PMCode => '

sub PDL::conv1d {
   my $opt = pop @_ if ref($_[$#_]) eq \'HASH\';
   die \'Usage: conv1d( a(m), kern(p), [o]b(m), {Options} )\'
      if $#_<1 || $#_>2;
   my($a,$kern) = @_;
   my $c = $#_ == 2 ? $_[2] : PDL->null;
   &PDL::_conv1d_int($a,$kern,$c,
		     !(defined $opt && exists $$opt{Boundary}) ? 0 :
		     lc $$opt{Boundary} eq "reflect");
   return $c;
}

',
        Code => '
           int i,i1,i2,poff,pflip;
           double tmp;
           int reflect = $COMP(reflect);
           int m_size = $COMP(__m_size);
           int p_size = $COMP(__p_size);

           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;
           }
');


=head2 in

=for sig

  Signature: (a(); b(n); [o] c())

=cut

# this can be achieved by
#  ($a->dummy(0) == $b)->orover
# but this one avoids a larger intermediate and potentially shortcuts
pp_def('in',
	Pars => 'a(); b(n); [o] c()',
	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 threading 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 a piddle

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
piddle 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 piddle.  This follows the Matlab usage.

See L<uniqind|uniqind> if you need the indices of the unique
elements rather than the values.

=cut

EOPM

if ( $bvalflag ) {
	pp_addpm(<<'EOPM');

=for bad

Bad values are not considered unique by uniq and are ignored.

 $a=sequence(10);
 $a=$a->setbadif($a%3);
 print $a->uniq;
 [0 3 6 9]

=cut

EOPM
} # if: $bvalflag

pp_addpm(<<'EOPM');

*uniq = \&PDL::uniq;
# return unique elements of array
# find as jumps in the sorted array
# flattens in the process
sub PDL::uniq {
   use PDL::Core 'barf';
   my ($arr) = @_;
   return $arr if($arr->nelem == 0); # The null list is unique (CED)
   my $srt  = $arr->clump(-1)->where($arr==$arr)->qsort;  # no NaNs or BADs for qsort
   my $nans = $arr->clump(-1)->where($arr!=$arr);
   my $uniq = ($srt->nelem > 0) ? $srt->where($srt != $srt->rotate(-1)) : $srt;
   # make sure we return something if there is only one value
   my $answ = $nans;  # NaN values always uniq
   if ( $uniq->nelem > 0 ) {
      $answ = $uniq->append($answ);
   } else {
      $answ = ( ($srt->nelem == 0) ?  $srt : PDL::pdl( ref($srt), [$srt->index(0)] ) )->append($answ);
   }
   return $answ;
}

EOPM

pp_add_exported ('', 'uniqind');
pp_addpm (<< 'EOPM');

=head2 uniqind

=for ref

Return the indices of all unique elements of a piddle
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
piddle is lost.

See L<uniq|uniq> if you want the unique values instead of the
indices.

=cut

EOPM

if ($bvalflag ) {
	pp_addpm(<<'EOPM');

=for bad

Bad values are not considered unique by uniqind and are ignored.

=cut

EOPM
} # if: $bvalflag

pp_addpm(<<'EOPM');

*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 = $aflat->sequence->long->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 piddle 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|uniq> for a unique list of scalars; and
L<qsortvec|PDL::Ufunc/qsortvec> for sorting a list of vectors
lexicographcally.

=cut

EOPM

if ( $bvalflag ) {
pp_addpm(<<'EOPM');

=for bad

If a vector contains all bad values, it is ignored as in L<uniq|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

EOPM
} # if: $bvalflag

pp_addpm(<<'EOPM');

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 = null;
   $pdl2d = $pdl->mv(0,-1)->clump($pdl->ndims-1)->mv(-1,0);              # clump all but dim(0)

   my $ngood = null;
   $ngood = $pdl2d->ones->sumover;
   $ngood = $pdl2d->ngoodover if  ($PDL::Bad::Status && $pdl->badflag);  # number of good values each vector
   my $ngood2 = null;
   $ngood2 = $ngood->where($ngood);                                      # number of good values with no all-BADs

   $pdl2d = $pdl2d->mv(0,-1)->dice($ngood->which)->mv(-1,0);             # remove all-BAD vectors


   my $numnan = null;
   $numnan = ($pdl2d!=$pdl2d)->sumover;                                  # works since no all-BADs to confuse

   my $presrt = null;
   $presrt = $pdl2d->mv(0,-1)->dice($numnan->not->which)->mv(0,-1);      # remove vectors with any NaN values
   my $nanvec = null;
   $nanvec = $pdl2d->mv(0,-1)->dice($numnan->which)->mv(0,-1);           # the vectors with any NaN values

   # use dice instead of nslice since qsortvec might be packing
   # the badvals to the front of the array instead of the end like
   # the docs say. If that is the case and it gets fixed, it won't
   # bust uniqvec. DAL 14-March 2006

   my $srt = null;
   $srt = $presrt->qsortvec->mv(0,-1);                                   # BADs are sorted by qsortvec
   my $srtdice = $srt;
   my $somebad = null;
   if  ($PDL::Bad::Status && $srt->badflag) {
      $srtdice = $srt->dice($srt->mv(0,-1)->nbadover->not->which);
      $somebad = $srt->dice($srt->mv(0,-1)->nbadover->which);
   }

   my $uniq = null;
   if ($srtdice->nelem > 0) {
      $uniq = ($srtdice != $srtdice->rotate(-1))->mv(0,-1)->orover->which;
   } else {
      $uniq = $srtdice->orover->which;
   }

   my $ans = null;
   if ( $uniq->nelem > 0 ) {
      $ans = $srtdice->dice($uniq);
   } else {
      $ans = ($srtdice->nelem > 0) ? $srtdice->slice("0,:") : $srtdice;
   }
   return $ans->append($somebad)->append($nanvec->mv(0,-1))->mv(0,-1);
}

EOPM

#####################################################################
#  clipping routines
#####################################################################

# clipping

=head2 hclip

=for sig

  Signature: (a(); b(); [o] c())

clip (threshold) C<$a> by C<$b> (C<$b> is upper bound)

=head2 lclip

=for sig

  Signature: (a(); b(); [o] c())

clip (threshold) C<$a> by C<$b> (C<$b> is lower bound)

=cut

for my $opt (
	     ['hclip','>'],
	     ['lclip','<']
	     ) {
    my $name = $opt->[0];
    my $op   = $opt->[1];
    pp_def(
	   $name,
	   HandleBad => 1,
	   Pars => 'a(); b(); [o] c()',
	   Code =>
	   '$c() = ($a() '.$op.' $b()) ? $b() : $a();',
	   BadCode =>
	   'if ( $ISBAD(a()) || $ISBAD(b()) ) {
               $SETBAD(c());
            } else {
	       $c() = ($a() '.$op.' $b()) ? $b() : $a();
            }',
	   Doc =>  'clip (threshold) C<$a> by C<$b> (C<$b> is '.
	   ($name eq 'hclip' ? 'upper' : 'lower').' bound)',
          PMCode=><<"EOD",
sub PDL::$name {
   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::_${name}_int(\$a,\$b,\$c);
   return \$c;
}
EOD
    ); # pp_def $name

} # for: my $opt

pp_add_exported('', 'clip');

pp_addpm(<<'EOD');

=head2 clip

=for ref

Clip (threshold) a piddle by (optional) upper or lower bounds.

=for usage

 $b = $a->clip(0,3);
 $c = $a->clip(undef, $x);

=cut

EOD

    if ( $bvalflag ) {
	pp_addpm(<<'EOD');

=for bad

clip handles bad values since it is just a
wrapper around L<hclip|/hclip> and
L<lclip|/lclip>.

=cut

EOD
} # if: $bvalflag

pp_def(
	'clip',
	HandleBad => 1,
	Pars => 'a(); l(); h(); [o] c()',
	Code =>
	'$c() = ( $a() > $h() )   ?   $h()   :  ( $a() < $l()   ?   $l()   :   $a()   );',
	BadCode => <<'EOBC',
	 if( $ISBAD(a()) || $ISBAD(l()) || $ISBAD(h()) ) {
	   $SETBAD(c());
         } else {
           $c() = ( $a() > $h() )   ?   $h()   :  ( $a() < $l()   ?   $l()   :   $a()   );
         }
EOBC
       PMCode => <<'EOPM',
*clip = \&PDL::clip;
sub PDL::clip {
  my($a, $l, $h) = @_;
  my $d;
  unless(defined($l) || defined($h)) {
      # Deal with pathological case
      if($a->is_inplace) {
	  $a->set_inplace(0);
	  return $a;
      } else {
	  return $a->copy;
      }
  }

  if($a->is_inplace) {
      $a->set_inplace(0); $d = $a
  } elsif ($#_ > 2) {
      $d=$_[3]
  } else {
      $d = PDL->nullcreate($a);
  }
  if(defined($l) && defined($h)) {
      &PDL::_clip_int($a,$l,$h,$d);
  } elsif( defined($l) ) {
      &PDL::_lclip_int($a,$l,$d);
  } elsif( defined($h) ) {
      &PDL::_hclip_int($a,$h,$d);
  } else {
      die "This can't happen (clip contingency) - file a bug";
  }

  return $d;
}
EOPM
    ); # end of clip pp_def call

############################################################
# elementary statistics and histograms
############################################################

=head2 wtstat

=for sig

  Signature: (a(n); wt(n); avg(); [o]b(); int deg)

=cut

pp_def(
       'wtstat',
       HandleBad => 1,
       Pars => 'a(n); wt(n); avg(); [o]b();',
       OtherPars => 'int deg',
       Code =>
       '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;',
       BadCode =>
       'double wtsum = 0;
	double statsum = 0;
        int flag = 0;
	loop(n) %{
           if ( $ISGOOD(wt()) && $ISGOOD(a()) && $ISGOOD(avg()) ) {
              register double tmp;
              register int i;
	      wtsum += $wt();
	      tmp=1;
              for(i=0; i<$COMP(deg); i++)
                 tmp *= $a();
	      statsum += $wt() * (tmp - $avg());
              flag = 1;
           }
        %}
        if ( flag ) { $b() = statsum / wtsum; }
        else        { $SETBAD(b()); $PDLSTATESETBAD(b); }',
       CopyBadStatusCode => '',
       Doc => '

=for ref

Weighted statistical moment of given degree

This calculates a weighted statistic over the vector C<a>.
The formula is

 b() = (sum_i wt_i * (a_i ** degree - avg)) / (sum_i wt_i)

=cut

',
       BadDoc => '

=for bad

Bad values are ignored in any calculation; C<$b> will only
have its bad flag set if the output contains any bad data.

=cut

',
       );



pp_def('statsover',
	HandleBad => 1,
	Pars => 'a(n); w(n); float+ [o]avg(); float+ [o]prms(); int+ [o]median(); int+ [o]min(); int+ [o]max(); float+ [o]adev(); float+ [o]rms()',
	Code =>
	'$GENERIC(avg) tmp = 0;
         $GENERIC(avg) tmp1 = 0;
         $GENERIC(avg) diff = 0;
         $GENERIC(min) curmin, curmax;
	 $GENERIC(avg) norm = 0;
	 loop(n) %{             /* Accumulate sum and summed weight. */
            tmp += $a()*$w();
            norm += ($GENERIC(avg)) $w();
            if (!n) { curmin = $a(); curmax = $a();}
            if ($a() < curmin) {
                curmin = $a();
             } else if ($a() > curmax) {
                curmax = $a();
             }
         %}
	 $avg() = tmp / norm;  /* Find mean */
         $min() = curmin;
         $max() = curmax;

         /* Calculate the RMS and standard deviation. */
         tmp = 0;
	 loop(n) %{
            diff = ($a() - $avg());
            tmp += diff * diff * $w();
            tmp1 += fabs(diff) * $w();
         %}
	 $rms()  = sqrt ( tmp/norm );
	 $prms() = (norm>1) ? sqrt( tmp/(norm-1) ) : 0;
         $adev() = tmp1/norm ;
',
	BadCode =>
	'$GENERIC(avg) tmp = 0;
         $GENERIC(avg) tmp1 = 0;
         $GENERIC(avg) diff = 0;
         $GENERIC(min) curmin, curmax;
	 $GENERIC(w) norm = 0;
         int flag = 0;
         loop(n) %{
             /* perhaps should check w() for bad values too ? */
             if ( $ISGOOD(a()) ) {
	      tmp += $a()*$w();
              norm += $w();
 	      if (!flag) { curmin = $a(); curmax = $a(); flag=1; }
              if ($a() < curmin) {
                curmin = $a();
              } else if ($a() > curmax) {
                curmax = $a();
              }
            }
         %}
         /* have at least one valid point if flag == 1 */
         if ( flag ) {
           $avg() = tmp / norm; /* Find mean */
           $min() = curmin;
           $max() = curmax;

	   /* Calculate the RMS and standard deviation. */
           tmp = 0;
           loop(n) %{
              if ($ISGOOD(a())) {
                 diff = $a()-$avg();
                 tmp += diff * diff * $w();
                 tmp1 += fabs(diff) * $w();
              }
           %}
	   $rms() = sqrt( tmp/norm );
	   if(norm>1)
	   	   $prms() =  sqrt( tmp/(norm-1) );
	   else
	           $SETBAD(prms());
           $adev() = tmp1 / norm ;
         } else       {
           $SETBAD(avg());  $PDLSTATESETBAD(avg);
           $SETBAD(rms());  $PDLSTATESETBAD(rms);
           $SETBAD(adev()); $PDLSTATESETBAD(adev);
           $SETBAD(min());  $PDLSTATESETBAD(min);
           $SETBAD(max());  $PDLSTATESETBAD(max);
           $SETBAD(prms()); $PDLSTATESETBAD(prms);
         }',
      CopyBadStatusCode => '',
      PMCode => '

sub PDL::statsover {
   barf(\'Usage: ($mean,[$prms, $median, $min, $max, $adev, $rms]) = statsover($data,[$weights])\') if $#_>1;
   my ($data, $weights) = @_;
   $weights = $data->ones() if !defined($weights);

   my $median = $data->medover();
   my $mean = PDL->nullcreate($data);
   my $rms = PDL->nullcreate($data);
   my $min = PDL->nullcreate($data);
   my $max = PDL->nullcreate($data);
   my $adev = PDL->nullcreate($data);
   my $prms = PDL->nullcreate($data);
   &PDL::_statsover_int($data, $weights, $mean, $prms, $median, $min, $max, $adev, $rms);

   return $mean unless wantarray;
   return ($mean, $prms, $median, $min, $max, $adev, $rms);
}

',
      Doc => '

=for ref

Calculate useful statistics over a dimension of a piddle

=for usage

  ($mean,$prms,$median,$min,$max,$adev,$rms) = statsover($piddle, $weights);

This utility function calculates various useful
quantities of a piddle. These are:

=over 3

=item * the mean:

  MEAN = sum (x)/ N

with C<N> being the number of elements in x

=item * the population RMS deviation from the mean:

  PRMS = sqrt( sum( (x-mean(x))^2 )/(N-1)

The population deviation is the best-estimate of the deviation
of the population from which a sample is drawn.

=item * the median

The median is the 50th percentile data value.  Median is found by
L<medover|PDL::Ufunc/medover>, so WEIGHTING IS IGNORED FOR THE MEDIAN CALCULATION.

=item * the minimum

=item * the maximum

=item * the average absolute deviation:

  AADEV = sum( abs(x-mean(x)) )/N

=item * RMS deviation from the mean:

  RMS = sqrt(sum( (x-mean(x))^2 )/N)

(also known as the root-mean-square deviation, or the square root of the
variance)

=back

This operator is a projection operator so the calculation
will take place over the final dimension. Thus if the input
is N-dimensional each returned value will be N-1 dimensional,
to calculate the statistics for the entire piddle either
use C<clump(-1)> directly on the piddle or call C<stats>.

=cut

',
     BadDoc =>'

=for bad

Bad values are simply ignored in the calculation, effectively reducing
the sample size.  If all data are bad then the output data are marked bad.

=cut

',
);

pp_add_exported('','stats');
pp_addpm(<<'EOD');

=head2 stats

=for ref

Calculates useful statistics on a piddle

=for usage

 ($mean,$prms,$median,$min,$max,$adev,$rms) = stats($piddle,[$weights]);

This utility calculates all the most useful quantities in one call.
It works the same way as L</statsover>, except that the quantities are
calculated considering the entire input PDL as a single sample, rather
than as a collection of rows. See L</statsover> for definitions of the
returned quantities.

=cut

EOD

    if ( $bvalflag ) {
	pp_addpm(<<'EOD');

=for bad

Bad values are handled; if all input values are bad, then all of the output
values are flagged bad.

=cut

EOD
} # if: bvalflag
pp_addpm(<<'EOD');
*stats	  = \&PDL::stats;
sub PDL::stats {
    barf('Usage: ($mean,[$rms]) = stats($data,[$weights])') if $#_>1;
    my ($data,$weights) = @_;

    # Ensure that $weights is properly threaded over; this could be
    # done rather more efficiently...
    if(defined $weights) {
	$weights = pdl($weights) unless UNIVERSAL::isa($weights,'PDL');
	if( ($weights->ndims != $data->ndims) or
	    (pdl($weights->dims) != pdl($data->dims))->or
	  ) {
		$weights = $weights + zeroes($data)
	}
	$weights = $weights->flat;
    }

    return PDL::statsover($data->flat,$weights);
}
EOD

=head2 histogram

=for sig

  Signature: (in(n); int+[o] hist(m); double step; double min; int msize => m)

=cut

my $histogram_doc = <<'EOD';

=for ref

Calculates a histogram for given stepsize and minimum.

=for usage

 $h = histogram($data, $step, $min, $numbins);
 $hist = zeroes $numbins;  # Put histogram in existing piddle.
 histogram($data, $hist, $step, $min, $numbins);

The histogram will contain C<$numbins> bins starting from C<$min>, each
C<$step> wide. The value in each bin is the number of
values in C<$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 C<$a(10,12)> into C<$b(15)> and get the result
you want.

For a higher-level interface, see L<hist|PDL::Basic/hist>.

=for example

 pdl> p histogram(pdl(1,1,2),1,0,3)
 [0 2 1]

=cut

EOD

=head2 whistogram

=for sig

  Signature: (in(n); float+ wt(n);float+[o] hist(m); double step; double min; int msize => m)

=cut

my $whistogram_doc = <<'EOD';

=for ref

Calculates a histogram from weighted data for given stepsize and minimum.

=for usage

 $h = whistogram($data, $weights, $step, $min, $numbins);
 $hist = zeroes $numbins;  # Put histogram in existing piddle.
 whistogram($data, $weights, $hist, $step, $min, $numbins);

The histogram will contain C<$numbins> bins starting from C<$min>, each
C<$step> wide. The value in each bin is the sum of the values in C<$weights>
that correspond to values in C<$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 C<$a(10,12)> into C<$b(15)> and get the result
you want.

=for example

 pdl> p whistogram(pdl(1,1,2), pdl(0.1,0.1,0.5), 1, 0, 4)
 [0 0.2 0.5 0]

=cut

EOD


for(
    {Name => 'histogram',
     WeightPar => '',
     HistType => 'int+',
     HistOp => '++',
     Doc => $histogram_doc,
     },
    {Name => 'whistogram',
     WeightPar => 'float+ wt(n);',
     HistType => 'float+',
     HistOp => '+= $wt()',
     Doc => $whistogram_doc,
     }
    )
{
pp_def($_->{Name},
       Pars => 'in(n); '.$_->{WeightPar}.$_->{HistType}.  '[o] hist(m)',
       # set outdim by Par!
       OtherPars => 'double step; double min; int msize => m',
       HandleBad => 1,
       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}.';
	   %}
	%}',
       BadCode =>
       '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) %{
              if ( $ISGOOD(in()) ) {
	         j = (int) (($in()-min)/step);
	         if (j<0) j=0;
	         if (j > maxj) j = maxj;
	         ($hist(m => j))'.$_->{HistOp}.';
              }
	   %}
	%}',
	Doc=>$_->{Doc});
}

=head2 histogram2d

=for sig

  Signature: (ina(n); inb(n); int+[o] hist(ma,mb); double stepa; double mina; int masize => ma;
	             double stepb; double minb; int mbsize => mb;)

=cut

my $histogram2d_doc = <<'EOD';

=for ref

Calculates a 2d histogram.

=for usage

 $h = histogram2d($datax, $datay, $stepx, $minx,
       $nbinx, $stepy, $miny, $nbiny);
 $hist = zeroes $nbinx, $nbiny;  # Put histogram in existing piddle.
 histogram2d($datax, $datay, $hist, $stepx, $minx,
       $nbinx, $stepy, $miny, $nbiny);

The histogram will contain C<$nbinx> x C<$nbiny> bins, with the lower
limits of the first one at C<($minx, $miny)>, and with bin size
C<($stepx, $stepy)>.
The value in each bin is the number of
values in C<$datax> and C<$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

 pdl> p 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]
 ]

=cut

EOD

=head2 whistogram2d

=for sig

  Signature: (ina(n); inb(n); float+ wt(n);float+[o] hist(ma,mb); double stepa; double mina; int masize => ma;
	             double stepb; double minb; int mbsize => mb;)

=cut

my $whistogram2d_doc = <<'EOD';

=for ref

Calculates a 2d histogram from weighted data.

=for usage

 $h = whistogram2d($datax, $datay, $weights,
       $stepx, $minx, $nbinx, $stepy, $miny, $nbiny);
 $hist = zeroes $nbinx, $nbiny;  # Put histogram in existing piddle.
 whistogram2d($datax, $datay, $weights, $hist,
       $stepx, $minx, $nbinx, $stepy, $miny, $nbiny);

The histogram will contain C<$nbinx> x C<$nbiny> bins, with the lower
limits of the first one at C<($minx, $miny)>, and with bin size
C<($stepx, $stepy)>.
The value in each bin is the sum of the values in
C<$weights> that correspond to values in C<$datax> and C<$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

 pdl> p whistogram2d(pdl(1,1,1,2,2),pdl(2,1,1,1,1),pdl(0.1,0.2,0.3,0.4,0.5),1,0,3,1,0,3)
 [
  [  0   0   0]
  [  0 0.5 0.9]
  [  0 0.1   0]
 ]


=cut

EOD


for(
    {Name => 'histogram2d',
     WeightPar => '',
     HistType => 'int+',
     HistOp => '++',
     Doc => $histogram2d_doc,
	},
    {Name => 'whistogram2d',
     WeightPar => 'float+ wt(n);',
     HistType => 'float+',
     HistOp => '+= $wt()',
     Doc => $whistogram2d_doc,
	}
    )
{
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;',
       HandleBad => 1,
       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}.';
	   %}
	%}
	',
       BadCode =>
       '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) %{
              if ( $ISGOOD(ina()) && $ISGOOD(inb()) ) {
	         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=> $_->{Doc});
}


###########################################################
# a number of constructors: fibonacci, append, axisvalues &
# random numbers
###########################################################

=head2 fibonacci

=for sig

  Signature: ([o]x(n))

Constructor - a vector with Fibonacci's sequence

=cut

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_Indx i=0;
        $GENERIC() x1, x2;

        x1 = 1; x2 = 0;

        loop(n) %{
           $x() = x1 + x2;
           if (i++>0) {
              x2 = x1;
              x1 = $x();
           }
        %}
');

=head2 append

=for sig

  Signature: (a(n); b(m); [o] c(mn))

=cut

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->ndims > 0 ? dpdla->dims[0] : 1) +
                        (dpdlb->ndims > 0 ? dpdlb->dims[0] : 1);
		',
	Code => 'register PDL_Indx mnp;
		 PDL_Indx ns = $SIZE(n);
                 threadloop %{
                       loop(n) %{ $c(mn => n) = $a(); %}
		       loop(m) %{ mnp = m+ns; $c(mn => mnp) = $b(); %}
		 %}',
	Doc => '

=for ref

append two piddles by concatenating along their 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 dimensions. The rest of the
dimensions must be compatible in the threading sense. The resulting
size of the first dimension is the sum of the sizes of the first dimensions
of the two argument piddles - i.e. C<n + m>.

Similar functions include L<glue|/glue> (below), which can append more
than two piddles along an arbitrary dimension, and
L<cat|PDL::Core/cat>, which can append more than two piddles that all
have the same sized dimensions.

=cut

'
   );

pp_addpm(<<'EOD')

=head2 glue

=for usage

  $c = $a->glue(<dim>,$b,...)

=for ref

Glue two or more PDLs together along an arbitrary dimension
(N-D L<append|append>).

Sticks $a, $b, and all following arguments together along the
specified dimension.  All other dimensions must be compatible in the
threading sense.

Glue is permissive, in the sense that every PDL is treated as having an
infinite number of trivial dimensions of order 1 -- so C<< $a->glue(3,$b) >>
works, even if $a and $b are only one dimensional.

If one of the PDLs has no elements, it is ignored.  Likewise, if one
of them is actually the undefined value, it is treated as if it had no
elements.

If the first parameter is a defined perl scalar rather than a pdl,
then it is taken as a dimension along which to glue everything else,
so you can say C<$cube = PDL::glue(3,@image_list);> if you like.

C<glue> is implemented in pdl, using a combination of L<xchg|PDL::Slices/xchg> and
L<append|append>.  It should probably be updated (one day) to a pure PP
function.

Similar functions include L<append|/append> (above), which appends
only two piddles along their first dimension, and
L<cat|PDL::Core/cat>, which can append more than two piddles that all
have the same sized dimensions.

=cut

sub PDL::glue{
    my($a) = shift;
    my($dim) = shift;

    if(defined $a && !(ref $a)) {
	my $b = $dim;
	$dim = $a;
	$a = $b;
    }

    if(!defined $a || $a->nelem==0) {
	return $a unless(@_);
	return shift() if(@_<=1);
	$a=shift;
	return PDL::glue($a,$dim,@_);
    }

    if($dim - $a->dim(0) > 100) {
	print STDERR "warning:: PDL::glue allocating >100 dimensions!\n";
    }
    while($dim >= $a->ndims) {
	$a = $a->dummy(-1,1);
    }
    $a = $a->xchg(0,$dim);

    while(scalar(@_)){
	my $b = shift;
	next unless(defined $b && $b->nelem);

	while($dim >= $b->ndims) {
		$b = $b->dummy(-1,1);
        }
	$b = $b->xchg(0,$dim);
	$a = $a->append($b);
    }
    $a->xchg(0,$dim);
}




EOD
;

=head2 axisvalues

=for sig

  Signature: ([o,nc]a(n))

=cut

pp_def( 'axisvalues',
	Pars => '[o,nc]a(n)',
	Code => 'loop(n) %{ $a() = n; %}',
	Doc => '

=for ref

Internal routine

C<axisvalues> is the internal primitive that implements
L<axisvals|PDL::Basic/axisvals>
and alters its argument.

=cut

'
       ); # pp_def: axisvalues


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 L<zeroes|PDL::Core/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.

You can use the perl function L<srand|perlfunc/srand> to seed the random
generator. For further details consult Perl's  L<srand|perlfunc/srand>
documentation.

=head2 randsym

=for ref

Constructor which returns piddle of random numbers

=for usage

 $a = randsym([type], $nx, $ny, $nz,...);
 $a = randsym $b;

etc (see L<zeroes|PDL::Core/zeroes>).

This is the uniform distribution between 0 and 1 (excluding both 0 and
1, cf L<random|/random>). The arguments are the same as C<zeroes> (q.v.) -
i.e. one can specify dimensions, types or give a template.

You can use the perl function L<srand|perlfunc/srand> to seed the random
generator. For further details consult Perl's  L<srand|perlfunc/srand>
documentation.

=cut

EOD

pp_addhdr(<<'EOH');

#ifndef Drand01
#define Drand01() (((double)rand()) / (RAND_MAX+1.0))
#endif

EOH

pp_def(
	'random',
	Pars=>'a();',
	PMFunc => '',
	Code =>
	'$a() = Drand01();',
	'NoPthread' => 1, # random isn't threadsafe
	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',
	'NoPthread' => 1, # random isn't threadsafe
	Pars=>'a();',
	PMFunc => '',
	Code =>
	'double tmp;
	 do tmp = Drand01(); while (tmp == 0.0); /* 0 < tmp < 1 */
         $a() = tmp;',
	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 L<zeroes|PDL::Core/zeroes>).

This is generated using the math library routine C<ndtri>.

Mean = 0, Stddev = 1


You can use the perl function L<srand|perlfunc/srand> to seed the random
generator. For further details consult Perl's  L<srand|perlfunc/srand>
documentation.

=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');

###############################################################
# binary searches in a piddle; various forms
###############################################################

pp_add_exported('','vsearch');

# generic front end; defaults to vsearch_sample for backwards compatibility

pp_addpm(<<'EOD');

=head2 vsearch

=for sig

  Signature: ( vals(); xs(n); [o] indx(); [\%options] )

=for ref

Efficiently search for values in a sorted piddle, returning indices.

=for usage

  $idx = vsearch( $vals, $x, [\%options] );
  vsearch( $vals, $x, $idx, [\%options ] );

B<vsearch> performs a binary search in the ordered piddle C<$x>,
for the values from C<$vals> piddle, returning indices into C<$x>.
What is a "match", and the meaning of the returned indices, are determined
by the options.

The C<mode> option indicates which method of searching to use, and may
be one of:

=over

=item C<sample>

invoke B<vsearch_sample>, returning indices appropriate for sampling
within a distribution.

=item C<insert_leftmost>

invoke B<vsearch_insert_leftmost>, returning the left-most possible
insertion point which still leaves the piddle sorted.

=item C<insert_rightmost>

invoke B<vsearch_insert_rightmost>, returning the right-most possible
insertion point which still leaves the piddle sorted.

=item C<insert_match>

invoke B<vsearch_match>, returning the index of a matching element,
else -(insertion point + 1)

=item C<insert_bin_inclusive>

invoke B<vsearch_bin_inclusive>, returning an index appropriate for binning
on a grid where the left bin edges are I<inclusive> of the bin. See
below for further explanation of the bin.

=item C<insert_bin_exclusive>

invoke B<vsearch_bin_exclusive>, returning an index appropriate for binning
on a grid where the left bin edges are I<exclusive> of the bin. See
below for further explanation of the bin.

=back

The default value of C<mode> is C<sample>.

=cut

sub vsearch {
    my $opt = 'HASH' eq ref $_[-1]
            ? pop
	    : { mode => 'sample' };

    croak( "unknown options to vsearch\n" )
	if ( ! defined $opt->{mode} && keys %$opt )
	|| keys %$opt > 1;

    my $mode = $opt->{mode};
    goto
        $mode eq 'sample'           ? \&vsearch_sample
      : $mode eq 'insert_leftmost'  ? \&vsearch_insert_leftmost
      : $mode eq 'insert_rightmost' ? \&vsearch_insert_rightmost
      : $mode eq 'match'            ? \&vsearch_match
      : $mode eq 'bin_inclusive'    ? \&vsearch_bin_inclusive
      : $mode eq 'bin_exclusive'    ? \&vsearch_bin_exclusive
      :                               croak( "unknown vsearch mode: $mode\n" );
}

*PDL::vsearch = \&vsearch;

EOD

use Text::Tabs qw[ expand ];
sub undent {
    my $txt = expand( shift );

    $txt =~ s/^([ \t]+)-{4}.*$//m;
    $txt =~ s/^$1//mg
      if defined $1;
    $txt;
}

for my $func ( [
        vsearch_sample => {
            low  => -1,
            high => '$SIZE(n)',
	    up   => '($x(n => n1) > $x(n => 0))',
            code => q[
                   while ( high - low > 1 ) {
                       mid = %MID%;
                       if ( ( value > $x(n => mid ) ) == up ) low = mid;
                       else                                   high = mid;
                   }
                   $idx() = low >= n1 ? n1
                         : up        ? low + 1
                         : low < 0   ? 0
                         :           low ;
                   ----
           ],
            ref =>
              'Search for values in a sorted array, return index appropriate for sampling from a distribution',

            doc_pre => q[
			 B<%FUNC%> returns an index I<I> for each value I<V> of C<$vals> appropriate
                         for sampling C<$vals>
			 ----
			 ],
            doc_incr => q[
				   V <= x[0]  : I = 0
			   x[0]  < V <= x[-1] : I s.t. x[I-1] < V <= x[I]
			   x[-1] < V          : I = $x->nelem -1
			 ----
			 ],

            doc_decr => q[
				    V > x[0]  : I = 0
			   x[0]  >= V > x[-1] : I s.t. x[I] >= V > x[I+1]
			   x[-1] >= V         : I = $x->nelem - 1
			 ----
			 ],

            doc_post => q[
			  If all elements of C<$x> are equal, I<< I = $x->nelem - 1 >>.

			  If C<$x> contains duplicated elements, I<I> is the index of the
			  leftmost (by position in array) duplicate if I<V> matches.

			  =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 = %FUNC%($b, $a); # Now, $c will have the appropriate distr.

			  It is possible to use the L<cumusumover|PDL::Ufunc/cumusumover>
			  function to obtain cumulative probabilities from absolute probabilities.
			  ----
			  ],

        },
    ],

    [
        # return left-most possible insertion point.
        # lowest index where x[i] >= value
        vsearch_insert_leftmost => {
            low  => 0,
            high => 'n1',
            code => q[
		    while (low <= high ) {
                        mid = %MID%;
			if ( ( $x(n => mid) >= value ) == up ) high = mid - 1;
			else                                   low  = mid + 1;
		    }
		    $idx() = up ? low : high;
	    ],
            ref =>
              'Determine the insertion point for values in a sorted array, inserting before duplicates.',

            doc_pre => q[
			 B<%FUNC%> returns an index I<I> for each value I<V> of
			 C<$vals> equal to the leftmost position (by index in array) within
			 C<$x> that I<V> may be inserted and still maintain the order in
			 C<$x>.

			 Insertion at index I<I> involves shifting elements I<I> and higher of
			 C<$x> to the right by one and setting the now empty element at index
			 I<I> to I<V>.
			 ----
			 ],
            doc_incr => q[
				   V <= x[0]  : I = 0
			   x[0]  < V <= x[-1] : I s.t. x[I-1] < V <= x[I]
			   x[-1] < V          : I = $x->nelem
			 ----
			 ],

            doc_decr => q[
				    V >  x[0]  : I = -1
			   x[0]  >= V >= x[-1] : I s.t. x[I] >= V > x[I+1]
			   x[-1] >= V          : I = $x->nelem -1
			 ----
			 ],

            doc_post => q[
			  If all elements of C<$x> are equal,

			      i = 0

			  If C<$x> contains duplicated elements, I<I> is the index of the
			  leftmost (by index in array) duplicate if I<V> matches.
			  ----
			  ],

        },
    ],

    [
        # return right-most possible insertion point.
        # lowest index where x[i] > value
        vsearch_insert_rightmost => {
            low  => 0,
            high => 'n1',
            code => q[
		   while (low <= high ) {
		       mid = %MID%;
		       if ( ( $x(n => mid) > value ) == up ) high = mid - 1;
		       else                                  low  = mid + 1;
		   }
		   $idx() = up ? low : high;
            ],
            ref =>
              'Determine the insertion point for values in a sorted array, inserting after duplicates.',

            doc_pre => q[
			 B<%FUNC%> returns an index I<I> for each value I<V> of
			 C<$vals> equal to the rightmost position (by index in array) within
			 C<$x> that I<V> may be inserted and still maintain the order in
			 C<$x>.

			 Insertion at index I<I> involves shifting elements I<I> and higher of
			 C<$x> to the right by one and setting the now empty element at index
			 I<I> to I<V>.
			 ----
			 ],
            doc_incr => q[
				    V < x[0]  : I = 0
			   x[0]  <= V < x[-1] : I s.t. x[I-1] <= V < x[I]
			   x[-1] <= V         : I = $x->nelem
			 ----
			 ],

            doc_decr => q[
				   V >= x[0]  : I = -1
			   x[0]  > V >= x[-1] : I s.t. x[I] >= V > x[I+1]
			   x[-1] > V          : I = $x->nelem -1
			 ----
			 ],

            doc_post => q[
			  If all elements of C<$x> are equal,

			      i = $x->nelem - 1

			  If C<$x> contains duplicated elements, I<I> is the index of the
			  leftmost (by index in array) duplicate if I<V> matches.
			  ----
			  ],

        },

    ],
    [
        # return index of matching element, else -( insertion point + 1 )
        # patterned after the Java binarySearch interface; see
        # http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html
        vsearch_match => {
            low  => 0,
            high => 'n1',
            code => q[
                   int done = 0;

                   while (low <= high ) {
                       $GENERIC() mid_value;

                       mid = %MID%;

                       mid_value = $x(n=>mid);

                       if ( up ) {
			   if      ( mid_value > value ) { high = mid - 1; }
			   else if ( mid_value < value ) { low  = mid + 1; }
			   else                          { done = 1; break; }
                       }
                       else {
			   if      ( mid_value < value ) { high = mid - 1; }
			   else if ( mid_value > value ) { low  = mid + 1; }
			   else                          { done = 1; break; }
                       }
                   }
                   $idx() = done ? mid
                         :   up ? - ( low  + 1 )
                         :        - ( high + 1 );
	       ],
            ref => 'Match values against a sorted array.',

            doc_pre => q[
			 B<%FUNC%> returns an index I<I> for each value I<V> of
			 C<$vals>.  If I<V> matches an element in C<$x>, I<I> is the
			 index of that element, otherwise it is I<-( insertion_point + 1 )>,
			 where I<insertion_point> is an index in C<$x> where I<V> may be
			 inserted while maintaining the order in C<$x>.  If C<$x> has
			 duplicated values, I<I> may refer to any of them.
			 ----
			 ],

        },
    ],
    [
        # x[i] is the INnclusive left edge of the bin
        # return i, s.t. x[i] <= value < x[i+1].
        # returns -1 if x[0] > value
        # returns N-1 if x[-1] <= value
        vsearch_bin_inclusive => {
            low  => 0,
            high => 'n1',
            code => q[
                   while (low <= high ) {
                       mid = %MID%;
                       if ( ( $x(n => mid) <= value ) == up ) low  = mid + 1;
                       else                                   high = mid - 1;
                   }
                   $idx() = up ? high: low;
            ],
            ref =>
              'Determine the index for values in a sorted array of bins, lower bound inclusive.',

            doc_pre => q[
			 C<$x> represents the edges of contiguous bins, with the first and
			 last elements representing the outer edges of the outer bins, and the
			 inner elements the shared bin edges.

			 The lower bound of a bin is inclusive to the bin, its outer bound is exclusive to it.
                         B<%FUNC%> returns an index I<I> for each value I<V> of C<$vals>
			 ----
			 ],
            doc_incr => q[
				    V < x[0]  : I = -1
			   x[0]  <= V < x[-1] : I s.t. x[I] <= V < x[I+1]
			   x[-1] <= V         : I = $x->nelem - 1
			 ----
			 ],

            doc_decr => q[
				    V >= x[0]  : I = 0
			   x[0]  >  V >= x[-1] : I s.t. x[I+1] > V >= x[I]
			   x[-1] >  V          : I = $x->nelem
			 ----
			 ],

            doc_post => q[
			  If all elements of C<$x> are equal,

			      i = $x->nelem - 1

			  If C<$x> contains duplicated elements, I<I> is the index of the
			  righmost (by index in array) duplicate if I<V> matches.
			  ----
			  ],

        },
    ],

    [
        # x[i] is the EXclusive left edge of the bin
        # return i, s.t. x[i] < value <= x[i+1].
        # returns -1 if x[0] >= value
        # returns N-1 if x[-1] < value
        vsearch_bin_exclusive => {
            low  => 0,
            high => 'n1',
            code => q[
                   while (low <= high ) {
                       mid = %MID%;
                       if ( ( $x(n => mid) <  value ) == up ) low  = mid + 1;
                       else                                   high = mid - 1;
                   }
                   $idx() = up ? high: low;
            ],
            ref =>
              'Determine the index for values in a sorted array of bins, lower bound exclusive.',

            doc_pre => q[
			 C<$x> represents the edges of contiguous bins, with the first and
			 last elements representing the outer edges of the outer bins, and the
			 inner elements the shared bin edges.

			 The lower bound of a bin is exclusive to the bin, its upper bound is inclusive to it.
			 B<%FUNC%> returns an index I<I> for each value I<V> of C<$vals>.
			 ----
			 ],
            doc_incr => q[
				    V <= x[0]  : I = -1
			   x[0]  <  V <= x[-1] : I s.t. x[I] < V <= x[I+1]
			   x[-1] <  V          : I = $x->nelem - 1
			 ----
			 ],

            doc_decr => q[
				    V >  x[0]  : I = 0
			   x[0]  >= V >  x[-1] : I s.t. x[I-1] >= V > x[I]
			   x[-1] >= V          : I = $x->nelem
			 ----
			 ],

            doc_post => q[
			  If all elements of C<$x> are equal,

			      i = $x->nelem - 1

			  If C<$x> contains duplicated elements, I<I> is the index of the
			  righmost (by index in array) duplicate if I<V> matches.
			  ----
			  ],

        }
    ],

  )

{
    my ( $func, $algo ) = @$func;

    my %replace = (
        # calculate midpoint of range; ensure we don't overflow
        # (low+high)>>1 for large values of low + high
	# see sf.net bug #360
        '%MID%'  => 'low + (( high - low )>> 1);',

	# determine which way the data are sorted.  vsearch_sample
	# overrides this.
        '%UP%' => '$x(n => n1) >= $x(n => 0)',

        '%FUNC%' => $func,

        '%PRE%' => undent(
            q[
		    %DOC_PRE%
                    ----
		   ]
        ),



        '%BODY%' => undent(
            q[
		   I<I> has the following properties:

		   =over

		   =item *

		   if C<$x> is sorted in increasing order

		   %DOC_INCR%

		   =item *

		   if C<$x> is sorted in decreasing order

		   %DOC_DECR%

		   =back
		   ----
                   ]
        ),

        '%POST%' => undent(
            q[
                   %DOC_POST%
		   ----
                   ]
        ),

        map { ( "%\U$_%" => undent( $algo->{$_} ) ) } keys %$algo,
    );

    $replace{'%PRE%'} = '' unless defined $replace{'%DOC_PRE%'};
    $replace{'%BODY%'} = ''
      unless defined $replace{'%DOC_INCR%'} || defined $replace{'%DOC_DECR%'};
    $replace{'%POST%'} = '' unless defined $replace{'%DOC_POST%'};


    my $code = undent q[
                   PDL_Indx n1 = $SIZE(n)-1;
                   PDL_Indx low = %LOW%;
                   PDL_Indx high = %HIGH%;
                   PDL_Indx mid;

		   $GENERIC() value = $vals();

                   /* determine sort order of data */
                   int up = %UP%;
                   %CODE%
                   ----
               ];

    my $doc = undent q[
		   =for ref

		   %REF%

		   =for usage

		     $idx = %FUNC%($vals, $x);

		   C<$x> must be sorted, but may be in decreasing or increasing
		   order.

                   %PRE%
		   %BODY%
		   %POST%
                   ----
		   ];


    # redo until nothing changes
    for my $tref ( \$code, \$doc ) {
        1 while $$tref =~ s/(%[\w_]+%)/$replace{$1}/ge;
    }

    pp_def(
        $func,
        HandleBad    => 0,
        BadDoc       => 'needs major (?) work to handles bad values',
        Pars         => 'vals(); x(n); indx [o]idx()',
        GenericTypes => [ 'F', 'D' ],    # too restrictive ?
        Code         => $code,
	Doc          => $doc,
    );
}

###############################################################
# routines somehow related to interpolation
###############################################################

=head2 interpolate

=for sig

  Signature: (xi(); x(n); y(n); [o] yi(); int [o] err())

=cut

pp_def('interpolate',
       HandleBad => 0,
       BadDoc => 'needs major (?) work to handles bad values',
	Pars => 'xi(); x(n); y(n); [o] yi(); int [o] err()',
	GenericTypes => ['F','D'], # too restrictive ?
	Code => '
		 $GENERIC() d;
		 PDL_Indx n  = $SIZE(n);
		 PDL_Indx n1 = n-1;
		 int up = ($x(n => n1) > $x(n => 0));
                 PDL_Indx jl, jh, m;
                 int carp;

                 threadloop %{
                   jl = -1;
                   jh = n;
                   carp = 0;
  		   while (jh-jl > 1)  /* binary search */
    			{
      				m = (jh+jl) >> 1;
      				if ($xi() > $x(n => m) == up)
					jl = m;
      				else
					jh = m;
    			}
		   if (jl == -1) {
			if ($xi() != $x(n => 0)) carp = 1;
			jl = 0;
                   } else if (jh == n) {
			if ($xi() != $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)-$xi())/d;
		   $yi() = d*$y(n => jl) + (1-d)*$y(n => jh);
                   $err() = carp;
		%}
', Doc=><<'EOD');

=for ref

routine for 1D linear interpolation

=for usage

 ( $yi, $err ) = interpolate($xi, $x, $y)

Given a set of points C<($x,$y)>, use linear interpolation
to find the values C<$yi> at a set of points C<$xi>.

C<interpolate> uses a binary search to find the suspects, er...,
interpolation indices and therefore abscissas (ie C<$x>)
have to be I<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
C<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 sets the corresponding element of C<$err> to 1,
which is otherwise 0.

See also L<interpol|/interpol>, which uses the same routine,
differing only in the handling of extrapolation - an error message
is printed rather than returning an error piddle.

=cut

EOD

pp_add_exported('', 'interpol');
pp_addpm(<<'EOD');

=head2 interpol

=for sig

 Signature: (xi(); x(n); y(n); [o] yi())

=for ref

routine for 1D linear interpolation

=for usage

 $yi = interpol($xi, $x, $y)

C<interpol> uses the same search method as L<interpolate|/interpolate>,
hence C<$x> must be I<strictly> ordered (either increasing or decreasing).
The difference occurs in the handling of out-of-bounds values; here
an error message is printed.

=cut

# kept in for backwards compatability
sub interpol ($$$;$) {
    my $xi = shift;
    my $x  = shift;
    my $y  = shift;

    my $yi;
    if ( $#_ == 0 ) { $yi = $_[0]; }
    else            { $yi = PDL->null; }

    interpolate( $xi, $x, $y, $yi, my $err = PDL->null );
    print "some values had to be extrapolated\n"
	if any $err;

    return $yi if $#_ == -1;

} # sub: interpol()
*PDL::interpol = \&interpol;

EOD

pp_add_exported('','interpND');
pp_addpm(<<'EOD');

=head2 interpND

=for ref

Interpolate values from an N-D piddle, with switchable method

=for example

  $source = 10*xvals(10,10) + yvals(10,10);
  $index = pdl([[2.2,3.5],[4.1,5.0]],[[6.0,7.4],[8,9]]);
  print $source->interpND( $index );

InterpND acts like L<indexND|PDL::Slices/indexND>,
collapsing C<$index> by lookup
into C<$source>; but it does interpolation rather than direct sampling.
The interpolation method and boundary condition are switchable via
an options hash.

By default, linear or sample interpolation is used, with constant
value outside the boundaries of the source pdl.  No dataflow occurs,
because in general the output is computed rather than indexed.

All the interpolation methods treat the pixels as value-centered, so
the C<sample> method will return C<< $a->(0) >> for coordinate values on
the set [-0.5,0.5), and all methods will return C<< $a->(1) >> for
a coordinate value of exactly 1.


Recognized options:

=over 3

=item method

Values can be:

=over 3

=item * 0, s, sample, Sample (default for integer source types)

The nearest value is taken. Pixels are regarded as centered on their
respective integer coordinates (no offset from the linear case).

=item * 1, l, linear, Linear (default for floating point source types)

The values are N-linearly interpolated from an N-dimensional cube of size 2.

=item * 3, c, cube, cubic, Cubic

The values are interpolated using a local cubic fit to the data.  The
fit is constrained to match the original data and its derivative at the
data points.  The second derivative of the fit is not continuous at the
data points.  Multidimensional datasets are interpolated by the
successive-collapse method.

(Note that the constraint on the first derivative causes a small amount
of ringing around sudden features such as step functions).

=item * f, fft, fourier, Fourier

The source is Fourier transformed, and the interpolated values are
explicitly calculated from the coefficients.  The boundary condition
option is ignored -- periodic boundaries are imposed.

If you pass in the option "fft", and it is a list (ARRAY) ref, then it
is a stash for the magnitude and phase of the source FFT.  If the list
has two elements then they are taken as already computed; otherwise
they are calculated and put in the stash.

=back

=item b, bound, boundary, Boundary

This option is passed unmodified into L<indexND|PDL::Slices/indexND>,
which is used as the indexing engine for the interpolation.
Some current allowed values are 'extend', 'periodic', 'truncate', and 'mirror'
(default is 'truncate').

=item bad

contains the fill value used for 'truncate' boundary.  (default 0)

=item fft

An array ref whose associated list is used to stash the FFT of the source
data, for the FFT method.

=back

=cut

*interpND = *PDL::interpND;
sub PDL::interpND {
  my $source = shift;
  my $index = shift;
  my $options = shift;

  barf 'Usage: interp_nd($source,$index,[{%options}])\n'
    if(defined $options   and    ref $options ne 'HASH');

  my($opt) = (defined $options) ? $options : {};

  my($method)   = $opt->{m} || $opt->{meth} || $opt->{method} || $opt->{Method};
  if(!defined $method) {
	$method = ($source->type <= zeroes(long,1)->type) ?
	   	   'sample' :
	           'linear';
  }

  my($boundary) = $opt->{b} || $opt->{boundary} || $opt->{Boundary} || $opt->{bound} || $opt->{Bound} || 'extend';
  my($bad) = $opt->{bad} || $opt->{Bad} || 0.0;

  if($method =~ m/^s(am(p(le)?)?)?/i) {
    return $source->range(PDL::Math::floor($index+0.5),0,$boundary);
  }

  elsif (($method eq 1) || $method =~ m/^l(in(ear)?)?/i) {
    ## key: (ith = index thread; cth = cube thread; sth = source thread)
    my $d = $index->dim(0);
    my $di = $index->ndims - 1;

    # Grab a 2-on-a-side n-cube around each desired pixel
    my $samp = $source->range($index->floor,2,$boundary); # (ith, cth, sth)

    # Reorder to put the cube dimensions in front and convert to a list
    $samp = $samp->reorder( $di .. $di+$d-1,
			    0 .. $di-1,
			    $di+$d .. $samp->ndims-1) # (cth, ith, sth)
                  ->clump($d); # (clst, ith, sth)

    # Enumerate the corners of an n-cube and convert to a list
    # (the 'x' is the normal perl repeat operator)
    my $crnr = PDL::Basic::ndcoords( (2) x $index->dim(0) ) # (index,cth)
             ->mv(0,-1)->clump($index->dim(0))->mv(-1,0); # (index, clst)

    # a & b are the weighting coefficients.
    my($a,$b);
    my($indexwhere);
    ($indexwhere = $index->where( 0 * $index )) .= -10; # Change NaN to invalid
    {
      my $bb = PDL::Math::floor($index);
      $a = ($index - $bb)     -> dummy(1,$crnr->dim(1)); # index, clst, ith
      $b = ($bb + 1 - $index) -> dummy(1,$crnr->dim(1)); # index, clst, ith
    }

    # Use 1/0 corners to select which multiplier happens, multiply
    # 'em all together to get sample weights, and sum to get the answer.
    my $out0 =  ( ($a * ($crnr==1) + $b * ($crnr==0)) #index, clst, ith
		 -> prodover                          #clst, ith
		 );

    my $out = ($out0 * $samp)->sumover; # ith, sth

    # Work around BAD-not-being-contagious bug in PDL <= 2.6 bad handling code  --CED 3-April-2013
    if($PDL::Bad::Status and $source->badflag) {
	my $baddies = $samp->isbad->orover;
	$out = $out->setbadif($baddies);
    }

    return $out;

  } elsif(($method eq 3) || $method =~ m/^c(u(b(e|ic)?)?)?/i) {

      my ($d,@di) = $index->dims;
      my $di = $index->ndims - 1;

      # Grab a 4-on-a-side n-cube around each desired pixel
      my $samp = $source->range($index->floor - 1,4,$boundary) #ith, cth, sth
	  ->reorder( $di .. $di+$d-1, 0..$di-1, $di+$d .. $source->ndims-1 );
	                   # (cth, ith, sth)

      # Make a cube of the subpixel offsets, and expand its dims to
      # a 4-on-a-side N-1 cube, to match the slices of $samp (used below).
      my $b = $index - $index->floor;
      for my $i(1..$d-1) {
	  $b = $b->dummy($i,4);
      }

      # Collapse by interpolation, one dimension at a time...
      for my $i(0..$d-1) {
	  my $a0 = $samp->slice("(1)");    # Just-under-sample
	  my $a1 = $samp->slice("(2)");    # Just-over-sample
	  my $a1a0 = $a1 - $a0;

	  my $gradient = 0.5 * ($samp->slice("2:3")-$samp->slice("0:1"));
	  my $s0 = $gradient->slice("(0)");   # Just-under-gradient
	  my $s1 = $gradient->slice("(1)");   # Just-over-gradient

	  $bb = $b->slice("($i)");

	  # Collapse the sample...
	  $samp = ( $a0 +
		    $bb * (
			   $s0  +
			   $bb * ( (3 * $a1a0 - 2*$s0 - $s1) +
				   $bb * ( $s1 + $s0 - 2*$a1a0 )
				   )
			   )
		    );

	  # "Collapse" the subpixel offset...
	  $b = $b->slice(":,($i)");
      }

      return $samp;

  } elsif($method =~ m/^f(ft|ourier)?/i) {

     eval "use PDL::FFT;";
     my $fftref = $opt->{fft};
     $fftref = [] unless(ref $fftref eq 'ARRAY');
     if(@$fftref != 2) {
	 my $a = $source->copy;
	 my $b = zeroes($source);
	 fftnd($a,$b);
	 $fftref->[0] = sqrt($a*$a+$b*$b) / $a->nelem;
	 $fftref->[1] = - atan2($b,$a);
     }

     my $i;
     my $c = PDL::Basic::ndcoords($source);               # (dim, source-dims)
     for $i(1..$index->ndims-1) {
	 $c = $c->dummy($i,$index->dim($i))
     }
     my $id = $index->ndims-1;
     my $phase = (($c * $index * 3.14159 * 2 / pdl($source->dims))
		  ->sumover) # (index-dims, source-dims)
 	          ->reorder($id..$id+$source->ndims-1,0..$id-1); # (src, index)

     my $phref = $fftref->[1]->copy;        # (source-dims)
     my $mag = $fftref->[0]->copy;          # (source-dims)

     for $i(1..$index->ndims-1) {
	 $phref = $phref->dummy(-1,$index->dim($i));
	 $mag = $mag->dummy(-1,$index->dim($i));
     }
     my $out = cos($phase + $phref ) * $mag;
     $out = $out->clump($source->ndims)->sumover;

     return $out;
 }  else {
     barf("interpND: unknown method '$method'; valid ones are 'linear' and 'sample'.\n");
 }
}

EOD

##############################################################
# things related to indexing: one2nd, which, where
##############################################################

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 C<$a> clumped using C<clump(-1)>. This routine is
used in the old vector form of L<whichND|/whichND>, but is useful on
its own occasionally.

Returned piddles have the L<indx|PDL::Core/indx> datatype.  C<$indices> can have
values larger than C<< $a->nelem >> but negative values in C<$indices>
will not give the answer you expect.

=for example

 pdl> $a=pdl [[[1,2],[-1,1]], [[0,-3],[3,2]]]; $c=$a->clump(-1)
 pdl> $maxind=maximum_ind($c); p $maxind;
 6
 pdl> print one2nd($a, maximum_ind($c))
 0 1 1
 pdl> 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;
  $ind = indx($ind);
  my(@index);
  my $count=0;
  foreach (@dimension) {
    $index[$count++]=$ind % $_;
    $ind /= $_;
  }
  return @index;
}

EOD

=head2 which

=for sig

  Signature: (mask(n); indx [o] inds(m))

=cut

my $doc_which = <<'EOD';

=for ref

Returns indices of non-zero values from a 1-D PDL

=for usage

 $i = which($mask);

returns a pdl with indices for all those elements that are nonzero in
the mask. Note that the returned indices will be 1D. If you feed in a
multidimensional mask, it will be flattened before the indices are
calculated.  See also L<whichND|/whichND> for multidimensional masks.

If you want to index into the original mask or a similar piddle
with output from C<which>, remember to flatten it before calling index:

  $data = random 5, 5;
  $idx = which $data > 0.5; # $idx is now 1D
  $bigsum = $data->flat->index($idx)->sum;  # flatten before indexing

Compare also L<where|/where> for similar functionality.

SEE ALSO:

L<which_both|/which_both> returns separately the indices of both
zero and nonzero values in the mask.

L<where|/where> returns associated values from a data PDL, rather than
indices into the mask PDL.

L<whichND|/whichND> returns N-D indices into a multidimensional PDL.

=for example

 pdl> $x = sequence(10); p $x
 [0 1 2 3 4 5 6 7 8 9]
 pdl> $indx = which($x>6); p $indx
 [7 8 9]

=cut

EOD

=head2 which_both

=for sig

  Signature: (mask(n); indx [o] inds(m); indx [o]notinds(q))

=cut

my $doc_which_both = <<'EOD';

=for ref

Returns indices of zero and nonzero values in a mask PDL

=for usage

 ($i, $c_i) = which_both($mask);

This works just as L<which|/which>, but the complement of C<$i> will be in
C<$c_i>.

=for example

 pdl> $x = sequence(10); p $x
 [0 1 2 3 4 5 6 7 8 9]
 pdl> ($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); indx [o] inds(m);',
	  Variables => 'int dm=0;',
	  Elseclause => "",
	  Autosize => '$SIZE(m) = sum;',
	  Doc => $doc_which,
	  PMCode=><<'EOD',
   sub which { my ($this,$out) = @_;
		$this = $this->flat;
		$out = $this->nullcreate unless defined $out;
		PDL::_which_int($this,$out);
		return $out;
   }
   *PDL::which = \&which;
EOD
	  },
	 {Name => 'which_both',
	  Pars => 'mask(n); indx [o] inds(m); indx [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;',
	  Doc => $doc_which_both,
	  PMCode=><<'EOD',
   sub which_both { my ($this,$outi,$outni) = @_;
		$this = $this->flat;
		$outi = $this->nullcreate unless defined $outi;
		$outni = $this->nullcreate unless defined $outni;
		PDL::_which_both_int($this,$outi,$outni);
		return wantarray ? ($outi,$outni) : $outi;
   }
   *PDL::which_both = \&which_both;
EOD
	  }
	 )
{
    pp_def($_->{Name},
	   HandleBad => 1,
	   Doc => $_->{Doc},
	   Pars => $_->{Pars},
	   PMCode => $_->{PMCode},
	   Code => $_->{Variables} .
                 'loop(n) %{
		       if($mask()) {
				$inds(m => dm) = n;
				dm++;
			}'.$_->{Elseclause} . "\n".
		' %}',
	   BadCode => $_->{Variables} .
                 'loop(n) %{
			if ( $mask() && $ISGOOD($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_Indx sum = 0;
		/* not sure if this is necessary */
		pdl * dpdl = $PDL(mask);
		$GENERIC() *m_datap = (($GENERIC() *)(PDL_REPRP(dpdl)));
		PDL_Indx inc = PDL_REPRINC(dpdl,0);
		PDL_Indx offs = PDL_REPROFFS(dpdl);
		PDL_Indx i;

		if (dpdl->ndims != 1)
		  barf("dimflag currently works only with 1D pdls");

'.
($bvalflag ? '
		if(dpdl->state & PDL_BADVAL)
		  for (i=0; i<dpdl->dims[0]; i++) {
	 	 	$GENERIC() foo = *(m_datap+inc*i+offs);
	 	        if(foo && $ISGOODVAR(foo,mask) )sum++;
		}
	        else
':'').'
		for (i=0; i<dpdl->dims[0]; i++) {
 	 		$GENERIC() foo = *(m_datap+inc*i+offs);
	 	                if(foo) sum++;
		}

                '. $_->{Autosize} . '
		/* printf("RedoDimsCode: setting dim m to %ld\n",sum); */'
	   );
}

pp_addpm(<<'EOD'

=head2 where

=for ref

Use a mask to select values from one or more data PDLs

C<where> accepts one or more data piddles and a mask piddle.  It
returns a list of output piddles, corresponding to the input data
piddles.  Each output piddle is a 1-dimensional list of values in its
corresponding data piddle. The values are drawn from locations where
the mask is nonzero.

The output PDLs are still connected to the original data PDLs, for the
purpose of dataflow.

C<where> combines the functionality of L<which|/which> and L<index|PDL::Slices/index>
into a single operation.

BUGS:

While C<where> works OK for most N-dimensional cases, it does not
thread properly over (for example) the (N+1)th dimension in data
that is compared to an N-dimensional mask.  Use C<whereND> for that.

=for usage

 $i = $x->where($x+5 > 0); # $i contains those elements of $x
                           # where mask ($x+5 > 0) is 1
 $i .= -5;  # Set those elements (of $x) to -5. Together, these
            # commands clamp $x to a maximum of -5.

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);

Note: C<$i> is always 1-D, even if C<$x> is E<gt>1-D.

WARNING: The first argument
(the values) and the second argument (the mask) currently have to have
the exact same dimensions (or horrible things happen). You *cannot*
thread over a smaller mask, for example.


=cut

sub PDL::where {
    barf "Usage: where( \$pdl1, ..., \$pdlN, \$mask )\n" if $#_ == 0;

    if($#_ == 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_addpm(<<'EOD'

=head2 whereND

=for ref

C<where> with support for ND masks and threading

C<whereND> accepts one or more data piddles and a
mask piddle.  It returns a list of output piddles,
corresponding to the input data piddles.  The values
are drawn from locations where the mask is nonzero.

C<whereND> differs from C<where> in that the mask
dimensionality is preserved which allows for
proper threading of the selection operation over
higher dimensions.

As with C<where> the output PDLs are still connected
to the original data PDLs, for the purpose of dataflow.

=for usage

  $sdata = whereND $data, $mask
  ($s1, $s2, ..., $sn) = whereND $d1, $d2, ..., $dn, $mask

  where

    $data is M dimensional
    $mask is N < M dimensional
    dims($data) 1..N == dims($mask) 1..N
    with threading over N+1 to M dimensions

=for example

  $data   = sequence(4,3,2);   # example data array
  $mask4  = (random(4)>0.5);   # example 1-D mask array, has $n4 true values
  $mask43 = (random(4,3)>0.5); # example 2-D mask array, has $n43 true values
  $sdat4  = whereND $data, $mask4;   # $sdat4 is a [$n4,3,2] pdl
  $sdat43 = whereND $data, $mask43;  # $sdat43 is a [$n43,2] pdl

Just as with C<where>, you can use the returned value in an
assignment. That means that both of these examples are valid:

  # Used to create a new slice stored in $sdat4:
  $sdat4 = $data->whereND($mask4);
  $sdat4 .= 0;
  # Used in lvalue context:
  $data->whereND($mask4) .= 0;

=cut

sub PDL::whereND :lvalue {
   barf "Usage: whereND( \$pdl1, ..., \$pdlN, \$mask )\n" if $#_ == 0;

   my $mask = pop @_;  # $mask has 0==false, 1==true
   my @to_return;

   my $n = PDL::sum($mask);

   foreach my $arr (@_) {

      my $sub_i = $mask * ones($arr);
      my $where_sub_i = PDL::where($arr, $sub_i);

      # count the number of dims in $mask and $arr
      # $mask = a b c d e f.....
      my @idims = dims($arr);

      # ...and pop off the number of dims in $mask
      foreach ( dims($mask) ) { shift(@idims) };

      my $ndim = 0;
      foreach my $id ($n, @idims[0..($#idims-1)]) {
         $where_sub_i = $where_sub_i->splitdim($ndim++,$id) if $n>0;
      }

      push @to_return, $where_sub_i;
   }

   return (@to_return == 1) ? $to_return[0] : @to_return;
}
*whereND = \&PDL::whereND;

EOD
);

pp_add_exported("", 'whereND');

pp_addpm(<<'EOD'

=head2 whichND

=for ref

Return the coordinates of non-zero values in a mask.

=for usage

WhichND returns the N-dimensional coordinates of each nonzero value in
a mask PDL with any number of dimensions.  The returned values arrive
as an array-of-vectors suitable for use in
L<indexND|PDL::Slices/indexND> or L<range|PDL::Slices/range>.

 $coords = whichND($mask);

returns a PDL containing the coordinates of the elements that are non-zero
in C<$mask>, suitable for use in indexND.  The 0th dimension contains the
full coordinate listing of each point; the 1st dimension lists all the points.
For example, if $mask has rank 4 and 100 matching elements, then $coords has
dimension 4x100.

If no such elements exist, then whichND returns a structured empty PDL:
an Nx0 PDL that contains no values (but matches, threading-wise, with
the vectors that would be produced if such elements existed).

DEPRECATED BEHAVIOR IN LIST CONTEXT:

whichND once delivered different values in list context than in scalar
context, for historical reasons.  In list context, it returned the
coordinates transposed, as a collection of 1-PDLs (one per dimension)
in a list.  This usage is deprecated in PDL 2.4.10, and will cause a
warning to be issued every time it is encountered.  To avoid the
warning, you can set the global variable "$PDL::whichND" to 's' to
get scalar behavior in all contexts, or to 'l' to get list behavior in
list context.

In later versions of PDL, the deprecated behavior will disappear.  Deprecated
list context whichND expressions can be replaced with:

    @list = $a->whichND->mv(0,-1)->dog;


SEE ALSO:

L<which|/which> finds coordinates of nonzero values in a 1-D mask.

L<where|/where> extracts values from a data PDL that are associated
with nonzero values in a mask PDL.

=for example

 pdl> $a=sequence(10,10,3,4)
 pdl> ($x, $y, $z, $w)=whichND($a == 203); p $x, $y, $z, $w
 [3] [0] [2] [0]
 pdl> print $a->at(list(cat($x,$y,$z,$w)))
 203

=cut

*whichND = \&PDL::whichND;
sub PDL::whichND {
  my $mask = shift;
  $mask = PDL::pdl('PDL',$mask) unless(UNIVERSAL::isa($mask,'PDL'));

  # List context: generate a perl list by dimension
  if(wantarray) {
      if(!defined($PDL::whichND)) {
	  printf STDERR "whichND: WARNING - list context deprecated. Set \$PDL::whichND. Details in pod.";
      } elsif($PDL::whichND =~ m/l/i) {
	  # old list context enabled by setting $PDL::whichND to 'l'
	  my $ind=($mask->clump(-1))->which;
	  return $mask->one2nd($ind);
      }
      # if $PDL::whichND does not contain 'l' or 'L', fall through to scalar context
  }

  # Scalar context: generate an N-D index piddle

  unless($mask->nelem) {
      return PDL::new_from_specification('PDL',indx,$mask->ndims,0);
  }

  unless($mask->getndims) {
    return $mask ? pdl(indx,0) : PDL::new_from_specification('PDL',indx,0);
  }

  $ind = $mask->flat->which->dummy(0,$mask->getndims)->make_physical;
  if($ind->nelem==0) {
      # In the empty case, explicitly return the correct type of structured empty
      return PDL::new_from_specification('PDL',indx,$mask->ndims, 0);
  }

  my $mult = ones($mask->getndims)->long;
  my @mdims = $mask->dims;
  my $i;

  for $i(0..$#mdims-1) {
   # use $tmp for 5.005_03 compatibility
   (my $tmp = $mult->index($i+1)) .= $mult->index($i)*$mdims[$i];
  }

  for $i(0..$#mdims) {
   my($s) = $ind->index($i);
   $s /= $mult->index($i);
   $s %= $mdims[$i];
  }

  return $ind;
}

EOD
);

pp_add_exported("", 'whichND');

#
# Set operations suited for manipulation of the operations above.
#


pp_addpm(<<'EOD'

=head2 setops

=for ref

Implements simple set operations like union and intersection

=for usage

   Usage: $set = setops($a, <OPERATOR>, $b);

The operator can be C<OR>, C<XOR> or C<AND>. This is then applied
to C<$a> viewed as a set and C<$b> viewed as a set. Set theory says
that a set may not have two or more identical elements, but setops
takes care of this for you, so C<$a=pdl(1,1,2)> is OK. The functioning
is as follows:

=over

=item C<OR>

The resulting vector will contain the elements that are either in C<$a>
I<or> in C<$b> or both. This is the union in set operation terms

=item C<XOR>

The resulting vector will contain the elements that are either in C<$a>
or C<$b>, but not in both. This is

     Union($a, $b) - Intersection($a, $b)

in set operation terms.

=item C<AND>

The resulting vector will contain the intersection of C<$a> and C<$b>, so
the elements that are in both C<$a> and C<$b>. Note that for convenience
this operation is also aliased to L<intersect|intersect>.

=back

It should be emphasized that these routines are used when one or both of
the sets C<$a>, C<$b> are hard to calculate or that you get from a separate
subroutine.

Finally IDL users might be familiar with Craig Markwardt's C<cmset_op.pro>
routine which has inspired this routine although it was written independently
However the present routine has a few less options (but see the examples)

=for example

You will very often use these functions on an index vector, so that is
what we will show here. We will in fact something slightly silly. First
we will find all squares that are also cubes below 10000.

Create a sequence vector:

  pdl> $x = sequence(10000)

Find all odd and even elements:

  pdl> ($even, $odd) = which_both( ($x % 2) == 0)

Find all squares

  pdl> $squares= which(ceil(sqrt($x)) == floor(sqrt($x)))

Find all cubes (being careful with roundoff error!)

  pdl> $cubes= which(ceil($x**(1.0/3.0)) == floor($x**(1.0/3.0)+1e-6))

Then find all squares that are cubes:

  pdl> $both = setops($squares, 'AND', $cubes)

And print these (assumes that C<PDL::NiceSlice> is loaded!)

  pdl> p $x($both)
   [0 1 64 729 4096]

Then find all numbers that are either cubes or squares, but not both:

  pdl> $cube_xor_square = setops($squares, 'XOR', $cubes)

  pdl> p $cube_xor_square->nelem()
   112

So there are a total of 112 of these!

Finally find all odd squares:

  pdl> $odd_squares = setops($squares, 'AND', $odd)


Another common occurrence is to want to get all objects that are
in C<$a> and in the complement of C<$b>. But it is almost always best
to create the complement explicitly since the universe that both are
taken from is not known. Thus use L<which_both|which_both> if possible
to keep track of complements.

If this is impossible the best approach is to make a temporary:

This creates an index vector the size of the universe of the sets and
set all elements in C<$b> to 0

  pdl> $tmp = ones($n_universe); $tmp($b) .= 0;

This then finds the complement of C<$b>

  pdl> $C_b = which($tmp == 1);

and this does the final selection:

  pdl> $set = setops($a, 'AND', $C_b)

=cut

*setops = \&PDL::setops;

sub PDL::setops {

  my ($a, $op, $b)=@_;

  # Check that $a and $b are 1D.
  if ($a->ndims() > 1 || $b->ndims() > 1) {
     warn 'setops: $a and $b must be 1D - flattening them!'."\n";
     $a = $a->flat;
     $b = $b->flat;
  }

  #Make sure there are no duplicate elements.
  $a=$a->uniq;
  $b=$b->uniq;

  my $result;

  if ($op eq 'OR') {
    # Easy...
    $result = uniq(append($a, $b));
  } elsif ($op eq 'XOR') {
    # Make ordered list of set union.
    my $union = append($a, $b)->qsort;
    # Index lists.
    my $s1=zeroes(byte, $union->nelem());
    my $s2=zeroes(byte, $union->nelem());

    # Find indices which are duplicated - these are to be excluded
    #
    # We do this by comparing x with x shifted each way.
    my $i1 = which($union != rotate($union, 1));
    my $i2 = which($union != rotate($union, -1));
    #
    # We then mark/mask these in the s1 and s2 arrays to indicate which ones
    # are not equal to their neighbours.
    #
    my $ts;
    ($ts = $s1->index($i1)) .= 1 if $i1->nelem() > 0;
    ($ts = $s2->index($i2)) .= 1 if $i2->nelem() > 0;

    my $inds=which($s1 == $s2);

    if ($inds->nelem() > 0) {
      return $union->index($inds);
    } else {
      return $inds;
    }

  } elsif ($op eq 'AND') {
    # The intersection of the arrays.

    # Make ordered list of set union.
    my $union = append($a, $b)->qsort;

    return $union->where($union == rotate($union, -1));
  } else {
    print "The operation $op is not known!";
    return -1;
  }

}
EOD
);


pp_add_exported("", 'setops');



pp_addpm(<<'EOD'

=head2 intersect

=for ref

Calculate the intersection of two piddles

=for usage

   Usage: $set = intersect($a, $b);

This routine is merely a simple interface to L<setops|setops>. See
that for more information

=for example

Find all numbers less that 100 that are of the form 2*y and 3*x

 pdl> $x=sequence(100)
 pdl> $factor2 = which( ($x % 2) == 0)
 pdl> $factor3 = which( ($x % 3) == 0)
 pdl> $ii=intersect($factor2, $factor3)
 pdl> p $x($ii)
 [0 6 12 18 24 30 36 42 48 54 60 66 72 78 84 90 96]

=cut

*intersect = \&PDL::intersect;

sub PDL::intersect {

   return setops($_[0], 'AND', $_[1]);

}

EOD
);

pp_add_exported("", 'intersect');



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), Karl Glazebrook
(kgb@aaoepp.aao.gov.au), Craig DeForest (deforest@boulder.swri.edu)
and Jarle Brinchmann (jarle@astro.up.pt)
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.

Updated for CPAN viewing compatibility by David Mertens.

=cut

EOD


pp_done();