File: transform.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 (4195 lines) | stat: -rw-r--r-- 133,612 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
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
pp_addhdr("#include <sys/time.h>\n") unless $^O =~ /MSWin32/i;
pp_addpm({At=>'Top'},<<'+======EOD======');

=head1 NAME

PDL::Transform - Coordinate transforms, image warping, and N-D functions

=head1 SYNOPSIS

use PDL::Transform;

 my $t = new PDL::Transform::<type>(<opt>)

 $out = $t->apply($in)  # Apply transform to some N-vectors (Transform method)
 $out = $in->apply($t)  # Apply transform to some N-vectors (PDL method)

 $im1 = $t->map($im);   # Transform image coordinates (Transform method)
 $im1 = $im->map($t);   # Transform image coordinates (PDL method)

 $t2 = $t->compose($t1);  # compose two transforms
 $t2 = $t x $t1;          # compose two transforms (by analogy to matrix mult.)

 $t3 = $t2->inverse();    # invert a transform
 $t3 = !$t2;              # invert a transform (by analogy to logical "not")

=head1 DESCRIPTION

PDL::Transform is a convenient way to represent coordinate
transformations and resample images.  It embodies functions mapping
R^N -> R^M, both with and without inverses.  Provision exists for
parametrizing functions, and for composing them.  You can use this
part of the Transform object to keep track of arbitrary functions
mapping R^N -> R^M with or without inverses.

The simplest way to use a Transform object is to transform vector
data between coordinate systems.  The L<apply|/apply> method
accepts a PDL whose 0th dimension is coordinate index (all other
dimensions are threaded over) and transforms the vectors into the new
coordinate system.

Transform also includes image resampling, via the L<map|/map> method.
You define a coordinate transform using a Transform object, then use
it to remap an image PDL.  The output is a remapped, resampled image.

You can define and compose several transformations, then apply them
all at once to an image.  The image is interpolated only once, when
all the composed transformations are applied.

In keeping with standard practice, but somewhat counterintuitively,
the L<map|/map> engine uses the inverse transform to map coordinates
FROM the destination dataspace (or image plane) TO the source dataspace;
hence PDL::Transform keeps track of both the forward and inverse transform.

For terseness and convenience, most of the constructors are exported
into the current package with the name C<< t_<transform> >>, so the following
(for example) are synonyms:

  $t = new PDL::Transform::Radial();  # Long way

  $t = t_radial();                    # Short way

Several math operators are overloaded, so that you can compose and
invert functions with expression syntax instead of method syntax (see below).

=head1 EXAMPLE

Coordinate transformations and mappings are a little counterintuitive
at first.  Here are some examples of transforms in action:

   use PDL::Transform;
   $a = rfits('m51.fits');   # Substitute path if necessary!
   $ts = t_linear(Scale=>3); # Scaling transform

   $w = pgwin(xs);
   $w->imag($a);

   ## Grow m51 by a factor of 3; origin is at lower left.
   $b = $ts->map($a,{pix=>1});    # pix option uses direct pixel coord system
   $w->imag($b);

   ## Shrink m51 by a factor of 3; origin still at lower left.
   $c = $ts->unmap($a, {pix=>1});
   $w->imag($c);

   ## Grow m51 by a factor of 3; origin is at scientific origin.
   $d = $ts->map($a,$a->hdr);    # FITS hdr template prevents autoscaling
   $w->imag($d);

   ## Shrink m51 by a factor of 3; origin is still at sci. origin.
   $e = $ts->unmap($a,$a->hdr);
   $w->imag($e);

   ## A no-op: shrink m51 by a factor of 3, then autoscale back to size
   $f = $ts->map($a);            # No template causes autoscaling of output

=head1 OPERATOR OVERLOADS

=over 3

=item '!'

The bang is a unary inversion operator.  It binds exactly as
tightly as the normal bang operator.

=item 'x'

By analogy to matrix multiplication, 'x' is the compose operator, so these
two expressions are equivalent:

  $f->inverse()->compose($g)->compose($f) # long way
  !$f x $g x $f                           # short way

Both of those expressions are equivalent to the mathematical expression
f^-1 o g o f, or f^-1(g(f(x))).

=item '**'

By analogy to numeric powers, you can apply an operator a positive
integer number of times with the ** operator:

  $f->compose($f)->compose($f)  # long way
  $f**3                         # short way

=back

=head1 INTERNALS

Transforms are perl hashes.  Here's a list of the meaning of each key:

=over 3

=item func

Ref to a subroutine that evaluates the transformed coordinates.  It's
called with the input coordinate, and the "params" hash.  This
springboarding is done via explicit ref rather than by subclassing,
for convenience both in coding new transforms (just add the
appropriate sub to the module) and in adding custom transforms at
run-time. Note that, if possible, new C<func>s should support
L<inplace|PDL::Core/inplace> operation to save memory when the data are flagged
inplace.  But C<func> should always return its result even when
flagged to compute in-place.

C<func> should treat the 0th dimension of its input as a dimensional
index (running 0..N-1 for R^N operation) and thread over all other input
dimensions.

=item inv

Ref to an inverse method that reverses the transformation.  It must
accept the same "params" hash that the forward method accepts.  This
key can be left undefined in cases where there is no inverse.

=item idim, odim

Number of useful dimensions for indexing on the input and output sides
(ie the order of the 0th dimension of the coordinates to be fed in or
that come out).  If this is set to 0, then as many are allocated as needed.

=item name

A shorthand name for the transformation (convenient for debugging).
You should plan on using UNIVERAL::isa to identify classes of
transformation, e.g. all linear transformations should be subclasses
of PDL::Transform::Linear.  That makes it easier to add smarts to,
e.g., the compose() method.

=item itype

An array containing the name of the quantity that is expected from the
input piddle for the transform, for each dimension.  This field is advisory,
and can be left blank if there's no obvious quantity associated with
the transform.  This is analogous to the CTYPEn field used in FITS headers.

=item oname

Same as itype, but reporting what quantity is delivered for each
dimension.

=item iunit

The units expected on input, if a specific unit (e.g. degrees) is expected.
This field is advisory, and can be left blank if there's no obvious
unit associated with the transform.

=item ounit

Same as iunit, but reporting what quantity is delivered for each dimension.

=item params

Hash ref containing relevant parameters or anything else the func needs to
work right.

=item is_inverse

Bit indicating whether the transform has been inverted.  That is useful
for some stringifications (see the PDL::Transform::Linear
stringifier), and may be useful for other things.

=back

Transforms should be inplace-aware where possible, to prevent excessive
memory usage.

If you define a new type of transform, consider generating a new stringify
method for it.  Just define the sub "stringify" in the subclass package.
It should call SUPER::stringify to generate the first line (though
the PDL::Transform::Composition bends this rule by tweaking the
top-level line), then output (indented) additional lines as necessary to
fully describe the transformation.

=head1 NOTES

Transforms have a mechanism for labeling the units and type of each
coordinate, but it is just advisory.  A routine to identify and, if
necessary, modify units by scaling would be a good idea.  Currently,
it just assumes that the coordinates are correct for (e.g.)  FITS
scientific-to-pixel transformations.

Composition works OK but should probably be done in a more
sophisticated way so that, for example, linear transformations are
combined at the matrix level instead of just strung together
pixel-to-pixel.

=head1 MODULE INTERFACE

There are both operators and constructors.  The constructors are all
exported, all begin with "t_", and all return objects that are subclasses
of PDL::Transform.

The L<apply|/apply>, L<invert|/invert>, L<map|/map>,
and L<unmap|/unmap> methods are also exported to the C<PDL> package: they
are both Transform methods and PDL methods.

=cut

+======EOD======


pp_addpm({At=>'Bot'},<<'+======EOD======');

=head1 AUTHOR

Copyright 2002, 2003 Craig DeForest.  There is no warranty.  You are allowed
to redistribute this software under certain conditions.  For details,
see the file COPYING in the PDL distribution.  If this file is
separated from the PDL distribution, the copyright notice should be
included in the file.

=cut

package PDL::Transform;
use Carp;
use overload '""' => \&_strval;
use overload 'x' => \&_compose_op;
use overload '**' => \&_pow_op;
use overload '!'  => \&t_inverse;

use PDL;
use PDL::MatrixOps;

our $PI = 3.1415926535897932384626;
our $DEG2RAD = $PI / 180;
our $RAD2DEG = 180/$PI;
our $E  = exp(1);


#### little helper kludge parses a list of synonyms
sub _opt {
  my($hash) = shift;
  my($synonyms) = shift;
  my($alt) = shift;  # default is undef -- ok.
  local($_);
  foreach $_(@$synonyms){
    return (UNIVERSAL::isa($alt,'PDL')) ? PDL->pdl($hash->{$_}) : $hash->{$_}
    if defined($hash->{$_}) ;
  }
  return $alt;
}

######################################################################
#
# Stringification hack.  _strval just does a method search on stringify
# for the object itself.  This gets around the fact that stringification
# overload is a subroutine call, not a method search.
#

sub _strval {
  my($me) = shift;
  $me->stringify();
}

######################################################################
#
# PDL::Transform overall stringifier.  Subclassed stringifiers should
# call this routine first then append auxiliary information.
#
sub stringify {
  my($me) = shift;
  my($mestr) = (ref $me);
  $mestr =~ s/PDL::Transform:://;
  my $out = $mestr . " (" . $me->{name} . "): ";
  $out .= "fwd ". ((defined ($me->{func})) ? ( (ref($me->{func}) eq 'CODE') ? "ok" : "non-CODE(!!)" ): "missing")."; ";
  $out .= "inv ". ((defined ($me->{inv})) ?  ( (ref($me->{inv}) eq 'CODE') ? "ok" : "non-CODE(!!)" ):"missing").".\n";
}

+======EOD======

pp_add_exported('apply');
pp_addpm(<<'+======EOD_apply======');

=head2 apply

=for sig

  Signature: (data(); PDL::Transform t)

=for usage

  $out = $data->apply($t);
  $out = $t->apply($data);

=for ref

Apply a transformation to some input coordinates.

In the example, C<$t> is a PDL::Transform and C<$data> is a PDL to
be interpreted as a collection of N-vectors (with index in the 0th
dimension).  The output is a similar but transformed PDL.

For convenience, this is both a PDL method and a Transform method.

=cut

use Carp;

*PDL::apply = \&apply;
sub apply {
  my($me) = shift;
  my($from) = shift;

  if(UNIVERSAL::isa($me,'PDL')){
      my($a) = $from;
      $from = $me;
      $me = $a;
  }

  if(UNIVERSAL::isa($me,'PDL::Transform') && UNIVERSAL::isa($from,'PDL')){
      croak "Applying a PDL::Transform with no func! Oops.\n" unless(defined($me->{func}) and ref($me->{func}) eq 'CODE');
      my $result = &{$me->{func}}($from,$me->{params});
      $result->is_inplace(0); # clear inplace flag, just in case.
      return $result;
  } else {
      croak "apply requires both a PDL and a PDL::Transform.\n";
  }

}

+======EOD_apply======

pp_add_exported('invert');
pp_addpm(<<'+======EOD_invert======');

=head2 invert

=for sig

  Signature: (data(); PDL::Transform t)

=for usage

  $out = $t->invert($data);
  $out = $data->invert($t);

=for ref

Apply an inverse transformation to some input coordinates.

In the example, C<$t> is a PDL::Transform and C<$data> is a piddle to
be interpreted as a collection of N-vectors (with index in the 0th
dimension).  The output is a similar piddle.

For convenience this is both a PDL method and a PDL::Transform method.

=cut

*PDL::invert = \&invert;
sub invert {
  my($me) = shift;
  my($data) = shift;

  if(UNIVERSAL::isa($me,'PDL')){
      my($a) = $data;
      $data = $me;
      $me = $a;
  }

  if(UNIVERSAL::isa($me,'PDL::Transform') && UNIVERSAL::isa($data,'PDL')){
      croak "Inverting a PDL::Transform with no inverse! Oops.\n" unless(defined($me->{inv}) and ref($me->{inv}) eq 'CODE');
      my $result = &{$me->{inv}}($data, $me->{params});
      $result->is_inplace(0);  # make sure inplace flag is clear.
      return $result;
  } else {
      croak("invert requires a PDL and a PDL::Transform (did you want 'inverse' instead?)\n");
  }
}

+======EOD_invert======

pp_addhdr(<<'+==EOD_map_auxiliary==');


/*
 * Singular-value decomposition code is borrowed from
 * MatrixOps -- cut-and-pasted here because of linker trouble.
 * It's used by the auxiliary matrix manipulation code, below.
 *
 */

void pdl_xform_svd(PDL_Double *W, PDL_Double *Z, int nRow, int nCol)
{
  int i, j, k, EstColRank, RotCount, SweepCount, slimit;
  PDL_Double eps, e2, tol, vt, p, h2, x0, y0, q, r, c0, s0, c2, d1, d2;
  eps = 1e-6;
  slimit = nCol/4;
  if (slimit < 6.0)
    slimit = 6;
  SweepCount = 0;
  e2 = 10.0*nRow*eps*eps;
  tol = eps*.1;
  EstColRank = nCol;
  for (i=0; i<nCol; i++) {
    for (j=0; j<nCol; j++) {
      W[nCol*(nRow+i)+j] = 0.0;
    }
    W[nCol*(nRow+i)+i] = 1.0;  /* rjrw 7/7/99: moved this line out of j loop */
  }
  RotCount = EstColRank*(EstColRank-1)/2;
  while (RotCount != 0 && SweepCount <= slimit)
    {
      RotCount = EstColRank*(EstColRank-1)/2;
      SweepCount++;
      for (j=0; j<EstColRank-1; j++)
        {
          for (k=j+1; k<EstColRank; k++)
            {
              p = q = r = 0.0;
              for (i=0; i<nRow; i++)
                {
                  x0 = W[nCol*i+j]; y0 = W[nCol*i+k];
                  p += x0*y0; q += x0*x0; r += y0*y0;
                }
              Z[j] = q; Z[k] = r;
              if (q >= r)
                {
                  if (q<=e2*Z[0] || fabs(p)<=tol*q) RotCount--;
                  else
                    {
                      p /= q; r = 1 - r/q; vt = sqrt(4*p*p+r*r);
                      c0 = sqrt(fabs(.5*(1+r/vt))); s0 = p/(vt*c0);
                      for (i=0; i<nRow+nCol; i++)
                        {
                          d1 = W[nCol*i+j]; d2 = W[nCol*i+k];
                          W[nCol*i+j] = d1*c0+d2*s0; W[nCol*i+k] = -d1*s0+d2*c0;
                        }
                    }
                }
              else
                {
                  p /= r; q = q/r-1; vt = sqrt(4*p*p+q*q);
                  s0 = sqrt(fabs(.5*(1-q/vt)));
                  if (p<0) s0 = -s0;
                  c0 = p/(vt*s0);
                  for (i=0; i<nRow+nCol; i++)
                    {
                      d1 = W[nCol*i+j]; d2 = W[nCol*i+k];
                      W[nCol*i+j] = d1*c0+d2*s0; W[nCol*i+k] = -d1*s0+d2*c0;
                    }
                }
            }
        }
      while (EstColRank>=3 && Z[(EstColRank-1)]<=Z[0]*tol+tol*tol)
        EstColRank--;
    }
}

/*
 * PDL_xform_aux:
 *  This handles the matrix manipulation part of the Jacobian filtered
 *  mapping code.  It's separate from the main code because it's
 *  independent of the data type of the original arrays.
 *
 *Given a pre-allocated workspace  and
 * an integer set of coordinates, generate the discrete Jacobian
 * from the map, pad the singular values, and return the inverse
 * Jacobian, the largest singular value of the Jacobian itself, and
 * the determinant of the original Jacobian.  Boundary values use the
 * asymmetric discrete Jacobian; others use the symmetric discrete Jacobian.
 *
 * The map and workspace must be of type PDL_D.  If the dimensionality is
 * d, then the workspace must have at least 3*n^2+n elements.  The
 * inverse of the padded Jacobian is returned in the first n^2 elements.
 * The determinant of the original Jacobian gets stuffed into the n^2
 * element of the workspace. The largest padded singular value is returned.
 *
 */

PDL_Double PDL_xform_aux ( pdl *map, PDL_Indx *coords, PDL_Double *tmp, PDL_Double sv_min) {
  short ndims;
  PDL_Long i, j, k;
  PDL_Long offset;
  PDL_Double det;
  PDL_Double *jptr;
  PDL_Double *svptr;
  PDL_Double *aptr,*bptr;
  PDL_Double max_sv = 0.0;

  ndims = map->ndims-1;

  /****** Accumulate the Jacobian */
  /* Accumulate the offset into the map array */
  for( i=offset=0; i<ndims; i++)
    offset += coords[i] * map->dimincs[i+1];

  jptr = tmp + ndims*ndims;

  for( i=0; i<ndims; i++) {                    /* Loop over offset direction */
    char bot = (coords[i] <=0);
    char top = (coords[i] >= map->dims[i+1]-1);
    char symmetric = !(bot || top);
    PDL_Double *ohi,*olo;
    PDL_Long diff = map->dimincs[i+1];
    ohi = ((PDL_Double *)map->data) + ( offset + ( top ? 0 : diff ));
    olo = ((PDL_Double *)map->data) + ( offset - ( bot ? 0 : diff ));

    for( j=0; j<ndims; j++) {                 /* Loop over dimension */
       PDL_Double jel =   *ohi - *olo;

       ohi += map->dimincs[0];
       olo += map->dimincs[0];

       if(symmetric)
         jel /= 2;
       *(jptr++) = jel;
    }
  }


  /****** Singular-value decompose the Jacobian
   * The svd routine produces the squares of the singular values,
   * and requires normalization for one of the rotation matrices.
   */

  jptr =   tmp + ndims*ndims;
  svptr = tmp + 3*ndims*ndims;
  pdl_xform_svd(jptr,svptr,ndims,ndims);

  aptr = svptr;
  for (i=0;i<ndims;i++,aptr++)
    *aptr = sqrt(*aptr);


  /* fix-up matrices here */
  bptr = jptr;
  for(i=0; i<ndims;i++) {
    aptr = svptr;
    for(j=0;j<ndims;j++)
     *(bptr++) /= *(aptr++);
  }

  /****** Store the determinant, and pad the singular values as necessary.*/
  aptr = svptr;
  det = 1.0;
  for(i=0;i<ndims;i++) {
    det *= *aptr;
    if(*aptr < sv_min)
      *aptr = sv_min;
    if(*aptr > max_sv )
        max_sv = *aptr;
    aptr++;
  }

  /****** Generate the inverse matrix */
  /* Multiply B-transpose times 1/S times A-transpose. */
  /* since S is diagonal we just divide by the appropriate element. */
  /* */
  aptr = tmp  + ndims*ndims;
  bptr = aptr + ndims*ndims;
  jptr=  tmp;

  for(i=0;i<ndims;i++) {
    for(j=0;j<ndims;j++) {
        *jptr = 0;

        for(k=0;k<ndims;k++)
          *jptr += aptr[j*ndims + k] * bptr[k*ndims + i] / *svptr;

        jptr++;
    }
    svptr++;
  }

 *jptr = det;
  return max_sv;
}

+==EOD_map_auxiliary==

pp_add_exported('map');
pp_def('map',
        Pars=>'k0()',  # Dummy to set type (should match the type of "in").
        OtherPars=>'SV *in; SV *out; SV *map; SV *boundary; SV *method;
                    SV *big; SV *blur; SV *sv_min; SV *flux; SV *bv',
        Code => <<'+==EOD_map_c_code==',

/*
 * Pixel interpolation & averaging code
 *
 * Calls a common coordinate-transformation block (see following hdr)
 * that isn't dependent on the type of the input variable.
 *
 * The inputs are SVs to avoid hassling with threadloops; threading
 * is handled internally.  To simplify the threading business, any
 * thread dimensions should all be collapsed to a single one by the
 * perl front-end.
 *
 */

 short ndims;           /* Number of dimensions we're working in    */
 PDL_Double *tmp;           /* Workspace for prefrobnication            */
 PDL_Indx  *ovec;           /* output pixel loop vector                 */
 PDL_Indx  *ivec;           /* input pixel loop vector                  */
 PDL_Indx  *ibvec;          /* input pixel base offset vector           */
 PDL_Double *dvec;          /* Residual vector for linearization        */
 PDL_Double *tvec;          /* Temporary floating-point vector          */
 PDL_Double *acc;           /* Threaded accumulator                     */
 PDL_Double *wgt;           /* Threaded weight accumulator              */
 PDL_Double *wgt2;          /* Threaded weight accumulator for badval finding   */
 char   *bounds;            /* Boundary condition packed string         */
 PDL_Indx  *index_stash;    /* Stash to store the opening index of dim sample scans */
 char   method;             /* Method identifier (gets one of 'h','g')  */
 PDL_Long   big;            /* Max size of input footprint for each pix */
 PDL_Double blur;           /* Scaling of filter                        */
 PDL_Double sv_min;         /* minimum singular value                   */
 char flux;                 /* Flag to indicate flux conservation       */
 PDL_Double *map_ptr;
 PDL_Long i, j;
 $GENERIC() badval = SvNV($COMP(bv));
 #define HANNING_LOOKUP_SIZE 2500
 static PDL_Double hanning_lookup[HANNING_LOOKUP_SIZE + 2];
 static int needs_hanning_calc = 1;
 PDL_Double zeta;
 PDL_Double hanning_offset;

 #define GAUSSIAN_LOOKUP_SIZE 4000
 #define GAUSSIAN_MAXVAL 6.25  /* 2.5 HWHMs (square it) */
 static PDL_Double gaussian_lookup[GAUSSIAN_LOOKUP_SIZE + 2];
 static int needs_gaussian_calc = 1;

 pdl *in  = PDL->SvPDLV($COMP(in));
 pdl *out = PDL->SvPDLV($COMP(out));
 pdl *map = PDL->SvPDLV($COMP(map));

 PDL->make_physical(in);
 PDL->make_physical(out);
 PDL->make_physical(map);

 ndims = map->ndims -1;

#define ROUND16(a) ((((unsigned long) a) & 0xf == 0) ? (unsigned long) a : ((((unsigned long) a) + 15) & ~0xf))

 /*
  * Allocate all our dynamic workspaces at once
  * */
 ovec = (PDL_Indx *)(PDL->smalloc( (STRLEN)
                                   ( + ROUND16(sizeof(PDL_Indx)    * 3 * ndims)               // ovec, ivec, ibvec
                                     + ROUND16(sizeof(PDL_Double) * (3*ndims))                // dvec, tvec
                                     + ROUND16(sizeof(PDL_Double) * in->dims[ndims])          // acc
                                     + ROUND16(sizeof(PDL_Double) * in->dims[ndims])          // wgt
                                     + ROUND16(sizeof(PDL_Double) * in->dims[ndims])          // wgt2
                                     + ROUND16(sizeof(PDL_Double) * 3 * ndims*ndims + ndims)  // tmp (for PDL_xform_aux)
                                     + ROUND16(sizeof(char) * ndims)                          // bounds
                                     + ROUND16(sizeof(PDL_Indx)   * ndims)                    // index_stash
                                     )
                                   )
                );
 ivec   =      (PDL_Indx *) ROUND16(&(ovec[ndims]));
 ibvec  =      (PDL_Indx *) ROUND16(&(ivec[ndims]));
 dvec   =    (PDL_Double *)(ROUND16(&(ibvec[ndims])));
 tvec   =    (PDL_Double *) ROUND16(&(dvec[ndims]));
 acc    =    (PDL_Double *) ROUND16(&(tvec[ndims]));
 wgt    =    (PDL_Double *) ROUND16(&(acc[in->dims[ndims]]));
 wgt2   =    (PDL_Double *) ROUND16(&(wgt[in->dims[ndims]]));
 tmp    =    (PDL_Double *) ROUND16(&(wgt2[in->dims[ndims]]));
 bounds =          (char *)(ROUND16(&(tmp [3*ndims*ndims+ndims])));
 index_stash = (PDL_Indx *) ROUND16(&(bounds[ndims]));


/***
 * Fill in the boundary condition array
 */
 {
  char *bstr;
  STRLEN blen;
  bstr = SvPV($COMP(boundary),blen);

  if(blen == 0) {
    /* If no boundary is specified then every dim gets truncated */
    int i;
    for (i=0;i<ndims;i++)
      bounds[i] = 1;
  } else {
    int i;
    for(i=0;i<ndims;i++) {
      switch(bstr[i < blen ? i : blen-1 ]) {
      case '0': case 'f': case 'F':               /* forbid */
        bounds[i] = 0;
        break;
      case '1': case 't': case 'T':               /* truncate */
        bounds[i] = 1;
        break;
      case '2': case 'e': case 'E':               /* extend */
        bounds[i] = 2;
        break;
      case '3': case 'p': case 'P':               /* periodic */
        bounds[i] = 3;
        break;
      case '4': case 'm': case 'M':               /* mirror */
        bounds[i] = 4;
        break;
      default:
        {
          char buf[BUFSIZ];
          sprintf(buf,"Error in map: Unknown boundary condition '%c'",bstr[i]);
          barf("%s", buf);
        }
        break;
      }
    }
  }
 }

/***
 * Parse out the 'method', 'big', 'blur', and 'sv_min' arguments
 */
 big    = labs((PDL_Long)   (SvNV($COMP(big))));
 if(big <= 0)
   barf("%s","map: 'big' parameter must be >0");

 blur   = fabs((PDL_Double) (SvNV($COMP(blur))));
 if(blur < 0)
   barf("%s","map: 'blur' parameter must be >= 0");

 sv_min = fabs((PDL_Double) (SvNV($COMP(sv_min))));
 if(sv_min < 0)
   barf("%s","map: 'sv_min' parameter must be >= 0");

 flux   = (SvNV($COMP(flux)) != 0);

 {
  char *mstr;
  STRLEN mlen;
  mstr = SvPV($COMP(method),mlen);

  if(mlen==0)
        method = 'h';
  else switch(*mstr) {
    case 'H':                 // H - rigorous hanning window
      method='H'; break;
    case 'h':                 // h - lookup-table hanning window
      method = 'h';
      if( needs_hanning_calc ) {
         int i;
         for(i=0;i<HANNING_LOOKUP_SIZE;i++) {
           hanning_lookup[i] = 0.5 + 0.5 * cos(3.1415926536 / HANNING_LOOKUP_SIZE * i);
         }
         hanning_lookup[HANNING_LOOKUP_SIZE]   = 0;
         hanning_lookup[HANNING_LOOKUP_SIZE+1] = 0;
         needs_hanning_calc = 0;
      }
      zeta = HANNING_LOOKUP_SIZE / blur;
      hanning_offset = (blur >= 1) ?
                0 :
                0.5 * (1.0 - blur);
      break;

    case 'g': case 'j':       // Gaussian and/or Jacobian, using lookup table
      method = 'g';
      zeta = GAUSSIAN_LOOKUP_SIZE / GAUSSIAN_MAXVAL;

      if( needs_gaussian_calc ) {
        int i;
	for(i=0;i<GAUSSIAN_LOOKUP_SIZE;i++) {
	  gaussian_lookup[i] = exp( - i * 1.386294 / zeta );
	}
	gaussian_lookup[GAUSSIAN_LOOKUP_SIZE]   = 0;
	gaussian_lookup[GAUSSIAN_LOOKUP_SIZE+1] = 0;
	needs_gaussian_calc = 0;
      }
      break;

    case 'G': case 'J':       // Jacobian -- same thing, with direct calculation
      method = 'G'; break;
    default:
      {
        char err[80];
        sprintf(err,"Bug in map: unknown method '%c'",*mstr);
        barf("%s", err);
      }
      break;
    }
 }



 /* End of initialization */
 /*************************************************************/
 /* Start of Real Work */

 /* Initialize coordinate vector and map offset
  */
 for(i=0;i<ndims;i++)
   ovec[i] = 0;

 map_ptr = (PDL_Double *)(map->data);


/* Main pixel loop (iterates over pixels in the output plane) */
 do {
   PDL_Indx psize; // Size of the region to accumulate over for this pixel
   PDL_Indx i_off; // Offset into the data array of the source PDL
   PDL_Indx j;     // Generic loop index
   char t_vio;     // counter used for truncation boundary violations
   char carry;     // flag used for multidimensional loop iteration

   /* Prefrobnicate the transformation matrix */
   psize = (PDL_Long)(blur * PDL_xform_aux(map, ovec, tmp, sv_min) + 0.5)+1; /* assignment */

#ifdef DEBUG_MAP
 {
     int k; PDL_Indx foo = 0;
     printf("ovec: [");
     for(k=0;k<ndims;k++) {
       foo += ovec[k] * map->dimincs[k+1];
       printf(" %2d ",(int)(ovec[k]));
     }
     printf("]; psize is %d; big is %d; blur is %8.2f; ret is %8g; map is [",psize,big, blur, ret);
     for(k=0;k<ndims;k++) {
       printf("%8.2f",(double)((($GENERIC() *)(map->data))[foo + k*map->dimincs[0]]));
     }
     printf("]\n");
 }
#endif

   /* Don't bother accumulating output if psize is too large */
   if(psize <= big) {
     /* Use the prefrobnicated matrix to generate a local linearization.
      * dvec gets the delta; ibvec gets the base.
      */
     {
       PDL_Double *mp = map_ptr;
       for (i=0;i<ndims;i++) {
        dvec[i]  = *mp - ( ibvec[i] = (PDL_Long)(*mp + 0.5));   /* assignment */
        mp += map->dimincs[0];
       }
     }

     /* Initialize input delta vector  */
     for(i=0;i<ndims;i++)
       ivec[i] = -psize;

     /* Initialize accumulators */
     {
       PDL_Double *ac = acc;
       for(i=0; i < in->dims[ndims]; i++)	
         *(ac++) = 0.0;		     

     }
     {
       PDL_Double *wg = wgt;
       for(i=0;i < in->dims[ndims]; i++)
         *(wg++) = 0.0;
     }
     {
       PDL_Double *wg = wgt2;
       for(i=0;i < in->dims[ndims]; i++)
         *(wg++) = 0.0;
      }	  


     /*
      * Calculate the original offset into the data array, to enable
      * delta calculations in the pixel loop
      *
      * i runs over dims; j holds the working integer index in the
      * current dim.
      *
      * This code matches the incrementation code at the bottom of the accumulation loop
      */
      
     t_vio = 0; /* truncation-boundary violation count - don't bother if it is nonzero */
     i_off = 0;
     for(i=0;i<ndims; i++) {
       j = ivec[i] + ibvec[i];
       if(j<0 || j >= in->dims[i]) {
         switch(bounds[i]) {
         case 0: /* no breakage allowed */
           barf("%s","index out-of-bounds in map");
           break;
         case 1: /* truncation */
           t_vio++;
           /* fall through */
         case 2: /* extension -- crop */
           if(j<0)
             j=0;
           else //if(j>=in->dims[i])
             j = in->dims[i] - 1;
           break;
         case 3: /* periodic -- mod it */
           j %= in->dims[i];
           if(j<0)
             j += in->dims[i];
           break;
         case 4: /* mirror -- reflect off the edges */
           j += in->dims[i];
           j %= (in->dims[i]*2);
           if(j<0)
             j += in->dims[i]*2;
           j -= in->dims[i];
           if(j<0) {
             j *= -1;
             j -= 1;
           }
           break;
         default:
           barf("%s", "Unknown boundary condition in map -- bug alert!");
           break;
         }
       }
       i_off += in->dimincs[i] * j;
     }

     /* Initialize index stashes for later reference as we scan the footprint */
     /* It's a pain in the ass to deal with boundaries, and doubly so at the  */
     /* end of a dimensional scan.  So we stash the index location at the     */
     /* start of each dimensional scan here.  When we finish incrementing     */
     /* through a particular dim, we pull its value back out of the stash.    */
     for(i=0;i<ndims;i++) {
       index_stash[i] = i_off; 
    }

     /* The input accumulation loop is the hotspot for the entire operation.        */
     /* We loop over pixels in the region of interest (+/- psize in each dimension) */
     /* in the input array, use the linearized transform to bring each pixel center */
     /* forward to the output plane, and calculate a weighting based on the chosen  */
     /* filter function.   'h' is a fast Hanning window rolloff using a lookup      */
     /* table that is initialized the first time through the code.  'H' is the      */
     /* same process, but explicitly calculated for each interation (~2x slower).   */
     /* 'g' uses a radial Gaussian filter.  Rather than calculate the array offset  */
     /* into the input array fresh from the current input array vector each time,   */
     /* we walk through the array using dimincs and the old offset.  This saves     */
     /* about half of the time spent on index calculation.                          */

     do {  /* Input accumulation loop */
         PDL_Double *cp;
         PDL_Double alpha; // weighting coefficient for the current point

       /* Calculate the weight of the current input point.  Don't bother if we're
        * violating any truncation boundaries (in that case our value is zero, but
        * for the interpolation we also set the weight to zero).
        */
       if( !t_vio ) {

         PDL_Double *ap = tvec;
         PDL_Double *bp = dvec;
         PDL_Indx   *ip = ivec;
         for(i=0; i<ndims; i++)
           *(ap++) = *(ip++) - *(bp++);

         switch(method) {
           PDL_Double dd; // tmp space for calculations in filters

         case 'h':
           /* This is the Hanning window rolloff.  It is a product of a simple */
           /* cos^2(theta) rolloff in each dimension.  Using a lookup table    */
           /* is about 2x faster than using cos(theta) directly in each        */
           /* weighting calculation, so we do.  Using 2500 entries and linear  */
           /* interpolation is accurate to about 10^-7, and should preserve    */
           /* the contents of cache pretty well.                               */
           alpha = 1;
           cp = tmp;
           for(i=0; i<ndims; i++) {
             int lodex;
             int hidex;
             PDL_Double beta;
              dd = 0;
             ap = tvec;
             /* Get the matrix-multiply element for this dimension */
             for(j=0;j<ndims; j++)
               dd += *(ap++) * *(cp++);

             /* Do linear interpolation from the table */
             /* The table captures a hanning window centered 0.5 pixel from center. */
             /* We scale the filter by the blur parameter -- but if blur is less    */
             /* than unity, we shrink the hanning blur window while keeping the 0.5 */
             /* value on the pixel edge at 0.5.  For blur greater than unity, we    */
             /* scale simply. */
             beta = fabs(dd) - hanning_offset;
             if(beta > 0) {
               if(beta >= blur) {
                 alpha = 0;
                 i = ndims;
               } else {
                 beta *= zeta;
                 lodex = beta;
                 beta -= lodex;
                 if(lodex > HANNING_LOOKUP_SIZE)
                 lodex = HANNING_LOOKUP_SIZE;
                 hidex = lodex+1;
                 alpha *= hanning_lookup[hidex]*beta + hanning_lookup[lodex]*(1-beta);
               } /* end of interpolation branch */
             } /* end of beta > 0 branch */
           } /* end of dimension loop */
         break;

        case 'H':
          /* This is the Hanning window rolloff with explicit calculation, preserved */
          /* in case someone actually wants the slower longer method. */
               alpha = 1;
               cp = tmp;
               for(i=0; i<ndims; i++) {
                 dd = 0;
                 ap = tvec;
                 for(j=0;j<ndims; j++)
                     dd += *(ap++) * *(cp++);
                 dd = (fabs(dd) - hanning_offset) / blur;
                 if( dd > 1 ) {
                     alpha = 0;
                     i = ndims;
                 } else
                     alpha *= (0.5 + 0.5 * cos( dd * 3.1415926536 ));
               }
              break;

	case 'g':
	  /* This is the Gaussian rolloff.  It does lookup into a precalculated exponential. */
	  {
	    PDL_Double sum = 0;
	    cp = tmp;
	    for(i=0; i<ndims;i++) {
	      dd = 0;
              ap = tvec;
	      for(j=0;j<ndims;j++)
	        dd += *(ap++) * *(cp++);
	      dd /= blur;
	      sum += dd * dd;
	      if(sum > GAUSSIAN_MAXVAL) {
		  i = ndims; /* exit early if we're too far out */
		  alpha = 0;
              }
	    }
	    if( sum > GAUSSIAN_MAXVAL ) {
	      alpha = 0;
	    } else {
	      int lodex,hidex;
	      PDL_Double beta = fabs(zeta * sum);
	      lodex = beta;
	      beta -= lodex;
	      hidex = lodex+1;
              alpha = gaussian_lookup[hidex]*beta + gaussian_lookup[lodex]*(1 - beta);
            }
          }
          break;

        case 'G':
          /* This is the Gaussian rolloff with explicit calculation, preserved */
          /* in case someone actually wants the slower longer method. */
              {
                 PDL_Double sum = 0;
                 cp = tmp;
                 for(i=0; i<ndims; i++) {
                   dd = 0;
                   ap = tvec;
                   for(j=0;j<ndims; j++)
                     dd += *(ap++) * *(cp++);
                   dd /= blur;
                   sum += dd * dd;
                   if(sum > 4) /* 2 pixels -- four half-widths */
                    i = ndims; /* exit early if this pixel is too far outside the footprint of the ideal point */
                 }

                 if(sum > GAUSSIAN_MAXVAL)
                   alpha = 0;
                 else
                   alpha = exp(-sum * 1.386294); /* Gaussian, rt(2)-pix HWHM */
              }
              break;
         default:
           {
             char buf[80];
             sprintf(buf,"This can't happen: method='%c'",method);
             barf("%s", buf);
           }
         }

         {  /* convenience block -- accumulate the current point into the weighted sum.  */
            /* This is more than simple assignment because we have our own explicit poor */
            /* man's threadloop here, so we accumulate each threaded element separately. */
            $GENERIC() *dat = (($GENERIC() *)(in->data)) + i_off;
            PDL_Indx max = out->dims[ndims];
            for( i=0; i < max; i++ ) {
	      if( (badval==0) || (*dat != badval) ) {
                 acc[i] += *dat * alpha;
                 dat += in->dimincs[ndims];
	         wgt[i] += alpha;
	      }
	      wgt2[i] += alpha;  // Accumulate what weight we would have with no bad values
            }
          }
       } /* end of t_vio check (i.e. of input accumulation) */


       /* Advance input accumulation loop.  */
       /* We both increment the total vector and also advance the index. */
       carry = 1;
       for(i=0; i<ndims && carry; i++) {
         /* Advance the current element of the offset vector */
         ivec[i]++;
         j = ivec[i] + ibvec[i];

         /* Advance the offset into the data array */
         if( j > 0 && j <= in->dims[i]-1 ) {
            /* Normal case -- just advance the input vector */
            i_off += in->dimincs[i];
         } else {
            /* Busted a boundary - either before or after.  */
            switch(bounds[i]){
            case 0: /* no breakage allowed -- treat as truncation for interpolation */
            case 1: /* truncation -- if we crossed the boundary mark ourselves out-of-bounds */
              if( j == 0 )
                t_vio--;
              else if( j == in->dims[i] )
                t_vio++;
              break;
             case 2: /* extension -- do nothing (so the same input point is re-used) */
               break;
             case 3: /* periodic  -- advance and mod into the allowed range */
               if((j % in->dims[i]) == 0) {
                 i_off -= in->dimincs[i] * (in->dims[i]-1);
               } else {
                 i_off += in->dimincs[i];
               }
               break;
            case 4: /* mirror -- advance or retreat depending on phase */
               j += in->dims[i];
               j %= (in->dims[i]*2);
               j -= in->dims[i];
               if( j!=0 && j!= -in->dims[i] ) {
                 if(j<0)
                   i_off -= in->dimincs[i];
                 else
                   i_off += in->dimincs[i];
               }
               break;
            }
         }

         /* Now check for carry */
         if(ivec[i] <= psize) {
           /* Normal case -- copy the current offset to the faster-running dim stashes */
           int k;
           for(k=0;k<i;k++) {
             index_stash[k] = i_off;
           }
           carry = 0;

         } else { /* End of this scan -- recover the last position, and mark carry */
           i_off = index_stash[i];
           if(bounds[i]==1) {
             j = ivec[i] + ibvec[i];
             if( j < 0 || j >= in->dims[i] )
               t_vio--;
             ivec[i] = -psize;
             j = ivec[i] + ibvec[i];
             if( j < 0 || j >= in->dims[i] )
               t_vio++;
             carry = 1;
           } else {
             ivec[i] = -psize;
           }
         }
       } /* End of counter-advance loop */
     } while(carry==0);  /* end of total data accumulation loop (termination condition has carry on last dim) */

     {
       PDL_Double *ac = acc;
       PDL_Double *wg = wgt;
       PDL_Double *wg2 = wgt2;
       $GENERIC() *dat = out->data;

       /* Calculate output vector offset */
       for(i=0;i<ndims;i++)
         dat += out->dimincs[i] * ovec[i];

       if(!flux) {
         /* Flux flag is NOT set -- normal case.  Copy the weighted accumulated data. */
         for(i=0; i < out->dims[ndims]; i++) {
	   if(*wg && (*wg2 / *wg) < 1.5 ) {
              *dat = *(ac++) / *(wg++);
	      wg2++;
           } else {
	      *dat = badval;
	      ac++; wg++; wg2++;
	   }
              dat += out->dimincs[ndims];
         }
       } else {
         /* Flux flag is set - scale by the (unpadded) determinant of the Jacobian */
         PDL_Double det = tmp[ndims*ndims];
         for(i=0; i < out->dims[ndims]; i++) {
	   if(*wg && (*wg2 / *wg) < 1.5 ) {
              *dat = *(ac++) / *(wg++) * det;
	      wg2++;
           } else {
	      *dat = badval;
	      ac++; wg++; wg2++;
	   }
           dat += out->dimincs[ndims];
         } /* end of for loop */
       } /* end of flux flag set conditional */
     } /* end of convenience block */
     
     /* End of code for normal pixels */
   } else {
     /* The pixel was ludicrously huge -- just set this pixel to nan */
     $GENERIC() *dat = out->data;
      for(i=0;i<ndims;i++)
        dat += out->dimincs[i] * ovec[i];
      for(i=0;i<out->dims[ndims];i++) {
        *dat = badval;          /* Should handle bad values too -- not yet */
        dat += out->dimincs[ndims];
      }
   }

   /* Increment the pixel counter */
   {
     for(i=0;
             (i<ndims) &&
             (map_ptr += map->dimincs[i+1]) &&  /* Funky pre-test increment */
             (++(ovec[i]) >= out->dims[i]);     /* Actual carry test */
         i++) {
        ovec[i] = 0;
        map_ptr -= out->dims[i] * map->dimincs[i+1];
     }
    }
  } while(i<ndims);


+==EOD_map_c_code==

        Doc=><<'+==EOD_map_doc==',

=head2 match

=for usage

  $b = $a->match($c);                  # Match $c's header and size
  $b = $a->match([100,200]);           # Rescale to 100x200 pixels
  $b = $a->match([100,200],{rect=>1}); # Rescale and remove rotation/skew.

=for ref

Resample a scientific image to the same coordinate system as another.

The example above is syntactic sugar for

 $b = $a->map(t_identity, $c, ...);

it resamples the input PDL with the identity transformation in
scientific coordinates, and matches the pixel coordinate system to
$c's FITS header.

There is one difference between match and map: match makes the
C<rectify> option to C<map> default to 0, not 1.  This only affects
matching where autoscaling is required (i.e. the array ref example
above).  By default, that example simply scales $a to the new size and
maintains any rotation or skew in its scientiic-to-pixel coordinate
transform.

=head2 map

=for usage

  $b = $a->map($xform,[<template>],[\%opt]); # Distort $a with transform $xform
  $b = $a->map(t_identity,[$pdl],[\%opt]); # rescale $a to match $pdl's dims.

=for ref

Resample an image or N-D dataset using a coordinate transform.

The data are resampled so that the new pixel indices are proportional
to the transformed coordinates rather than the original ones.

The operation uses the inverse transform: each output pixel location
is inverse-transformed back to a location in the original dataset, and
the value is interpolated or sampled appropriately and copied into the
output domain.  A variety of sampling options are available, trading
off speed and mathematical correctness.

For convenience, this is both a PDL method and a PDL::Transform method.

C<map> is FITS-aware: if there is a FITS header in the input data,
then the coordinate transform acts on the scientific coordinate system
rather than the pixel coordinate system.

By default, the output coordinates are separated from pixel coordinates
by a single layer of indirection.  You can specify the mapping between
output transform (scientific) coordinates to pixel coordinates using
the C<orange> and C<irange> options (see below), or by supplying a
FITS header in the template.

If you don't specify an output transform, then the output is
autoscaled: C<map> transforms a few vectors in the forward direction
to generate a mapping that will put most of the data on the image
plane, for most transformations.  The calculated mapping gets stuck in the
output's FITS header.

Autoscaling is especially useful for rescaling images -- if you specify
the identity transform and allow autoscaling, you duplicate the
functionality of L<rescale2d|PDL::Image2D/rescale2d>, but with more
options for interpolation.

You can operate in pixel space, and avoid autoscaling of the output,
by setting the C<nofits> option (see below).

The output has the same data type as the input.  This is a feature,
but it can lead to strange-looking banding behaviors if you use
interpolation on an integer input variable.

The C<template> can be one of:

=over 3

=item * a PDL

The PDL and its header are copied to the output array, which is then
populated with data.  If the PDL has a FITS header, then the FITS
transform is automatically applied so that $t applies to the output
scientific coordinates and not to the output pixel coordinates.  In
this case the NAXIS fields of the FITS header are ignored.

=item * a FITS header stored as a hash ref

The FITS NAXIS fields are used to define the output array, and the
FITS transformation is applied to the coordinates so that $t applies to the
output scientific coordinates.

=item * a list ref

This is a list of dimensions for the output array.  The code estimates
appropriate pixel scaling factors to fill the available space.  The
scaling factors are placed in the output FITS header.

=item * nothing

In this case, the input image size is used as a template, and scaling
is done as with the list ref case (above).

=back

OPTIONS:

The following options are interpreted:

=over 3

=item b, bound, boundary, Boundary (default = 'truncate')

This is the boundary condition to be applied to the input image; it is
passed verbatim to L<range|PDL::Slices/range> or
L<interpND|PDL::Primitive/interpND> in the sampling or interpolating
stage.  Other values are 'forbid','extend', and 'periodic'.  You can
abbreviate this to a single letter.  The default 'truncate' causes the
entire notional space outside the original image to be filled with 0.

=item pix, Pixel, nf, nofits, NoFITS (default = 0)

If you set this to a true value, then FITS headers and interpretation
are ignored; the transformation is treated as being in raw pixel coordinates.

=item j, J, just, justify, Justify (default = 0)

If you set this to 1, then output pixels are autoscaled to have unit
aspect ratio in the output coordinates.  If you set it to a non-1
value, then it is the aspect ratio between the first dimension and all
subsequent dimensions -- or, for a 2-D transformation, the scientific
pixel aspect ratio.  Values less than 1 shrink the scale in the first
dimension compared to the other dimensions; values greater than 1
enlarge it compared to the other dimensions.  (This is the same sense
as in the L<PGPLOT|PDL::Graphics::PGPLOT>interface.)

=item ir, irange, input_range, Input_Range

This is a way to modify the autoscaling.  It specifies the range of
input scientific (not necessarily pixel) coordinates that you want to be
mapped to the output image.  It can be either a nested array ref or
a piddle.  The 0th dim (outside coordinate in the array ref) is
dimension index in the data; the 1st dim should have order 2.
For example, passing in either [[-1,2],[3,4]] or pdl([[-1,2],[3,4]])
limites the map to the quadrilateral in input space defined by the
four points (-1,3), (-1,4), (2,4), and (2,3).

As with plain autoscaling, the quadrilateral gets sparsely sampled by
the autoranger, so pathological transformations can give you strange
results.

This parameter is overridden by C<orange>, below.

=item or, orange, output_range, Output_Range

This sets the window of output space that is to be sampled onto the
output array.  It works exactly like C<irange>, except that it specifies
a quadrilateral in output space.  Since the output pixel array is itself
a quadrilateral, you get pretty much exactly what you asked for.

This parameter overrides C<irange>, if both are specified.  It forces
rectification of the output (so that scientific axes align with the pixel
grid).

=item r, rect, rectify

This option defaults TRUE and controls how autoscaling is performed.  If
it is true or undefined, then autoscaling adjusts so that pixel coordinates
in the output image are proportional to individual scientific coordinates.
If it is false, then autoscaling automatically applies the inverse of any
input FITS transformation *before* autoscaling the pixels.  In the special
case of linear transformations, this preserves the rectangular shape of the
original pixel grid and makes output pixel coordinate proportional to input
coordinate.

=item m, method, Method

This option controls the interpolation method to be used.
Interpolation greatly affects both speed and quality of output.  For
most cases the option is directly passed to
L<interpND|PDL::Primitive/interpnd> for interpolation.  Possible
options, in order from fastest to slowest, are:

=over 3


=item * s, sample (default for ints)

Pixel values in the output plane are sampled from the closest data value
in the input plane.  This is very fast but not very accurate for either
magnification or decimation (shrinking).  It is the default for templates
of integer type.

=item * l, linear (default for floats)

Pixel values are linearly interpolated from the closest data value in the
input plane.  This is reasonably fast but only accurate for magnification.
Decimation (shrinking) of the image causes aliasing and loss of photometry
as features fall between the samples.  It is the default for floating-point
templates.

=item * c, cubic

Pixel values are interpolated using an N-cubic scheme from a 4-pixel
N-cube around each coordinate value.  As with linear interpolation,
this is only accurate for magnification.

=item * f, fft

Pixel values are interpolated using the term coefficients of the
Fourier transform of the original data.  This is the most appropriate
technique for some kinds of data, but can yield undesired "ringing" for
expansion of normal images.  Best suited to studying images with
repetitive or wavelike features.

=item * h, hanning

Pixel values are filtered through a spatially-variable filter tuned to
the computed Jacobian of the transformation, with hanning-window
(cosine) pixel rolloff in each dimension.  This prevents aliasing in the
case where the image is distorted or shrunk, but allows small amounts
of aliasing at pixel edges wherever the image is enlarged.

=item * g, gaussian, j, jacobian

Pixel values are filtered through a spatially-variable filter tuned to
the computed Jacobian of the transformation, with radial Gaussian
rolloff.  This is the most accurate resampling method, in the sense of
introducing the fewest artifacts into a properly sampled data set.
This method uses a lookup table to speed up calculation of the Gaussian
weighting.

=item * G

This method works exactly like 'g' (above), except that the Gaussian
values are computed explicitly for every sample -- which is considerably
slower.

=back

=item blur, Blur (default = 1.0)

This value scales the input-space footprint of each output pixel in
the gaussian and hanning methods. It's retained for historical
reasons.  Larger values yield blurrier images; values significantly
smaller than unity cause aliasing.  The parameter has slightly
different meanings for Gaussian and Hanning interpolation.  For
Hanning interpolation, numbers smaller than unity control the
sharpness of the border at the edge of each pixel (so that blur=>0 is
equivalent to sampling for non-decimating transforms).  For
Gaussian interpolation, the blur factor parameter controls the
width parameter of the Gaussian around the center of each pixel.

=item sv, SV (default = 1.0)

This value lets you set the lower limit of the transformation's
singular values in the hanning and gaussian methods, limiting the
minimum radius of influence associated with each output pixel.  Large
numbers yield smoother interpolation in magnified parts of the image
but don't affect reduced parts of the image.

=item big, Big (default = 0.5)

This is the largest allowable input spot size which may be mapped to a
single output pixel by the hanning and gaussian methods, in units of
the largest non-thread input dimension.  (i.e. the default won't let
you reduce the original image to less than 5 pixels across).  This places
a limit on how long the processing can take for pathological transformations.
Smaller numbers keep the code from hanging for a long time; larger numbers
provide for photometric accuracy in more pathological cases.  Numbers larer
than 1.0 are silly, because they allow the entire input array to be compressed
into a region smaller than a single pixel.

Wherever an output pixel would require averaging over an area that is too
big in input space, it instead gets NaN or the bad value.

=item phot, photometry, Photometry

This lets you set the style of photometric conversion to be used in the
hanning or gaussian methods.  You may choose:

=over 3

=item * 0, s, surf, surface, Surface (default)

(this is the default): surface brightness is preserved over the transformation,
so features maintain their original intensity.  This is what the sampling
and interpolation methods do.

=item * 1, f, flux, Flux

Total flux is preserved over the transformation, so that the brightness
integral over image regions is preserved.  Parts of the image that are
shrunk wind up brighter; parts that are enlarged end up fainter.

=back

=back

VARIABLE FILTERING:

The 'hanning' and 'gaussian' methods of interpolation give
photometrically accurate resampling of the input data for arbitrary
transformations.  At each pixel, the code generates a linear
approximation to the input transformation, and uses that linearization
to estimate the "footprint" of the output pixel in the input space.
The output value is a weighted average of the appropriate input spaces.

A caveat about these methods is that they assume the transformation is
continuous.  Transformations that contain discontinuities will give
incorrect results near the discontinuity.  In particular, the 180th
meridian isn't handled well in lat/lon mapping transformations (see
L<PDL::Transform::Cartography>) -- pixels along the 180th meridian get
the average value of everything along the parallel occupied by the
pixel.  This flaw is inherent in the assumptions that underly creating
a Jacobian matrix.  Maybe someone will write code to work around it.
Maybe that someone is you.

BAD VALUES:

If your PDL was compiled with bad value support, C<map()> supports
bad values in the data array.  Bad values in the input array are
propagated to the output array.  The 'g' and 'h' methods will do some
smoothing over bad values:  if more than 1/3 of the weighted input-array
footprint of a given output pixel is bad, then the output pixel gets marked
bad.

=cut

+==EOD_map_doc==
        PMCode => <<'+==EOD_map_perlcode=='

sub PDL::match {
  # Set default for rectification to 0 for simple matching...
  if( ref($_[$#_]) ne 'HASH' ) {
      push(@_,{})
  }
  my @k = grep(m/^r(e(c(t)?)?)?/,keys %{$_[$#_]});
  unless(@k) {
      $_[$#_]->{rectify} = 0;
  }
  t_identity()->map(@_);
}


*PDL::map = \&map;
sub map {
  my($me) = shift;
  my($in) = shift;

  if(UNIVERSAL::isa($me,'PDL') && UNIVERSAL::isa($in,'PDL::Transform')) {
      my($a) = $in;
      $in = $me;
      $me = $a;
  }

  barf ("PDL::Transform::map: source is not defined or is not a PDL\n")
    unless(defined $in and  UNIVERSAL::isa($in,'PDL'));

  barf ("PDL::Transform::map: source is empty\n")
    unless($in->nelem);

  my($tmp) = shift;
  my($opt) = shift;

  # Check for options-but-no-template case
  if(ref $tmp eq 'HASH' && !(defined $opt)) {
    if(!defined($tmp->{NAXIS})) {  # FITS headers all have NAXIS.
      $opt = $tmp;
      $tmp = undef;
    }
  }

  croak("PDL::Transform::map: Option 'p' was ambiguous and has been removed. You probably want 'pix' or 'phot'.") if exists($opt->{'p'});

  $tmp = [$in->dims]  unless(defined($tmp));

  # Generate an appropriate output piddle for values to go in
  my($out);
  my(@odims);
  my($ohdr);
  if(UNIVERSAL::isa($tmp,'PDL')) {
    @odims = $tmp->dims;

    my($a);
    if(defined ($a = $tmp->gethdr)) {
      my(%b) = %{$a};
      $ohdr = \%b;
    }
  } elsif(ref $tmp eq 'HASH') {
    # (must be a fits header -- or would be filtered above)
    for my $i(1..$tmp->{NAXIS}){
      push(@odims,$tmp->{"NAXIS$i"});
    }
    # deep-copy fits header into output
    my %foo = %{$tmp};
    $ohdr = \%foo;
  } elsif(ref $tmp eq 'ARRAY') {
    @odims = @$tmp;
  } else {
    barf("map: confused about dimensions of the output array...\n");
  }

  if(scalar(@odims) < scalar($in->dims)) {
    my @idims = $in->dims;
    push(@odims, splice(@idims,scalar(@odims)));
  }

  $out = PDL::new_from_specification('PDL',$in->type,@odims);
  $out->sethdr($ohdr) if defined($ohdr);

  if($PDL::Bad::Status) {
    # set badflag on output all the time if possible, to account for boundary violations
    $out->badflag(1);
  }

  ##############################
  ## Figure out the dimensionality of the
  ## transform itself (extra dimensions come along for the ride)
  my $nd = $me->{odim} || $me->{idim} || 2;
  my @sizes = $out->dims;
  my @dd = @sizes;

  splice @dd,$nd; # Cut out dimensions after the end

  # Check that there are elements in the output fields...
  barf "map: output has no dims!\n"
        unless(@dd);
  my $ddtotal = 1;
  map {$ddtotal *= $_} @dd;
  barf "map: output has no elements (at least one dim is 0)!\n"
     unless($ddtotal);


  ##############################
  # If necessary, generate an appropriate FITS header for the output.

  my $nofits = _opt($opt, ['nf','nofits','NoFITS','pix','pixel','Pixel']);

  ##############################
  # Autoscale by transforming a subset of the input points' coordinates
  # to the output range, and pick a FITS header that fits the output
  # coordinates into the given template.
  #
  # Autoscaling always produces a simple, linear mapping in the FITS header.
  # We support more complex mappings (via t_fits) but only to match a pre-existing
  # FITS header (which doesn't use autoscaling).
  #
  # If the rectify option is set (the default) then the image is rectified
  # in scientific coordinates; if it is clear, then the existing matrix
  # is used, preserving any shear or rotation in the coordinate system.
  # Since we eschew CROTA whenever possible, the CDi_j formalism is used instead.
  my $f_in = (defined($in->hdr->{NAXIS}) ? t_fits($in,{ignore_rgb=>1}) : t_identity());

  unless((defined $out->gethdr && $out->hdr->{NAXIS})  or  $nofits) {
      print "generating output FITS header..." if($PDL::Transform::debug);

      $out->sethdr($in->hdr_copy) # Copy extraneous fields...
        if(defined $in->hdr);

      my $samp_ratio = 300;

      my $orange = _opt($opt, ['or','orange','output_range','Output_Range'],
                        undef);

      my $omin;
      my $omax;
      my $osize;


      my $rectify = _opt($opt,['r','rect','rectify','Rectify'],1);


      if (defined $orange) {
          # orange always rectifies the coordinates -- the output scientific
          # coordinates *must* align with the axes, or orange wouldn't make
          # sense.
        print "using user's orange..." if($PDL::Transform::debug);
        $orange = pdl($orange) unless(UNIVERSAL::isa($orange,'PDL'));
        barf "map: orange must be 2xN for an N-D transform"
          unless ( (($orange->dim(1)) == $nd )
                   && $orange->ndims == 2);

        $omin = $orange->slice("(0)");
        $omax = $orange->slice("(1)");
        $osize = $omax - $omin;

        $rectify = 1;

      } else {

          ##############################
          # Real autoscaling happens here.

          if(!$rectify and ref( $f_in ) !~ /Linear/i) {
              if( $f_in->{name} ne 'identity' ) {
                 print STDERR "Warning: map can't preserve nonlinear FITS distortions while autoscaling.\n";
              }
              $rectify=1;
          }

          my $f_tr = ( $rectify ?
                       $me x $f_in :
                       (  ($me->{name} eq 'identity') ?  # Simple optimization for match()
                          $me :                          # identity -- just matching
                          !$f_in x $me x $f_in           # common case
                       )
                       );

          my $samps = (pdl(($in->dims)[0..$nd-1]))->clip(0,$samp_ratio);

          my $coords = ndcoords(($samps + 1)->list);

          my $t;
          my $irange = _opt($opt, ['ir','irange','input_range','Input_Range'],
                            undef);

          # If input range is defined, sample that quadrilateral -- else
          # sample the quad defined by the boundaries of the input image.
          if(defined $irange) {
              print "using user's irange..." if($PDL::Transform::debug);
              $irange = pdl($irange) unless(UNIVERSAL::isa($irange,'PDL'));
              barf "map: irange must be 2xN for an N-D transform"
                  unless ( (($irange->dim(1)) == $nd )
                           && $irange->ndims == 2);

              $coords *= ($irange->slice("(1)") - $irange->slice("(0)")) / $samps;
              $coords += $irange->slice("(0)");
              $coords -= 0.5; # offset to pixel corners...
              $t = $me;
          } else {
              $coords *= pdl(($in->dims)[0..$nd-1]) / $samps;
              $coords -= 0.5; # offset to pixel corners...
              $t = $f_tr;
          }
          my $ocoords = $t->apply($coords)->mv(0,-1)->clump($nd);

          # discard non-finite entries
          my $oc2  = $ocoords->range(
              which(
                  $ocoords->
                  xchg(0,1)->
                  sumover->
                  isfinite
              )
              ->dummy(0,1)
              );

          $omin = $oc2->minimum;
          $omax = $oc2->maximum;

          $osize = $omax - $omin;
          my $tosize;
          ($tosize = $osize->where($osize == 0)) .= 1.0;
      }

      my ($scale) = $osize / pdl(($out->dims)[0..$nd-1]);

      my $justify = _opt($opt,['j','J','just','justify','Justify'],0);
      if($justify) {
          my $tmp; # work around perl -d "feature"
          ($tmp = $scale->slice("0")) *= $justify;
          $scale .= $scale->max;
          $scale->slice("0") /= $justify;
      }

      print "done with autoscale. Making fits header....\n" if($PDL::Transform::debug);
      if( $rectify ) {
          # Rectified header generation -- make a simple coordinate header with no
          # rotation or skew.
          print "rectify\n" if($PDL::Transform::debug);
          for my $d(1..$nd) {
              $out->hdr->{"CRPIX$d"} = 1 + ($out->dim($d-1)-1)/2 ;
              $out->hdr->{"CDELT$d"} = $scale->at($d-1);
              $out->hdr->{"CRVAL$d"} = ( $omin->at($d-1) + $omax->at($d-1) ) /2 ;
              $out->hdr->{"NAXIS$d"} = $out->dim($d-1);
              $out->hdr->{"CTYPE$d"} = ( (defined($me->{otype}) ?
                                          $me->{otype}->[$d-1] : "")
                                         || $in->hdr->{"CTYPE$d"}
                                         || "");
              $out->hdr->{"CUNIT$d"} = ( (defined($me->{ounit}) ?
                                          $me->{ounit}->[$d-1] : "")
                                         || $in->hdr->{"CUNIT$d"}
                                         || $in->hdr->{"CTYPE$d"}
                                         || "");
          }
          $out->hdr->{"NAXIS"} = $nd;

          $out->hdr->{"SIMPLE"} = 'T';
          $out->hdr->{"HISTORY"} .= "Header written by PDL::Transform::Cartography::map";

          ### Eliminate fancy newfangled output header pointing tags if they exist
          ### These are the CROTA<n>, PCi_j, and CDi_j.
          for $k(keys %{$out->hdr})      {
              if( $k=~m/(^CROTA\d*$)|(^(CD|PC)\d+_\d+[A-Z]?$)/ ){
                  delete $out->hdr->{$k};
              }
          }
      } else {
          # Non-rectified output -- generate a CDi_j matrix instead of the simple formalism.
          # We have to deal with a linear transformation: we've got:  (scaling) x !input x (t x input),
          # where input is a linear transformation with offset and scaling is a simple scaling. We have
          # the scaling parameters and the matrix for !input -- we have only to merge them and then we
          # can write out the FITS header in CDi_j form.
          print "non-rectify\n" if($PDL::Transform::debug);
          my $midpoint_val = (pdl(($out->dims)[0..$nd-1])/2 * $scale)->apply( $f_in );
          print "midpoint_val is $midpoint_val\n" if($PDL::Transform::debug);
          # linear transformation
          unless(ref($f_in) =~ m/Linear/) {
              croak("Whups -- got a nonlinear t_fits transformation.  Can't deal with it.");
          }

          my $inv_sc_mat = zeroes($nd,$nd);
          $inv_sc_mat->diagonal(0,1) .= $scale;
          my $mat = $f_in->{params}->{matrix} x $inv_sc_mat;
          print "scale is $scale; mat is $mat\n" if($PDL::Transform::debug);

          print "looping dims 1..$nd: " if($PDL::Transform::debug);
          for my $d(1..$nd) {
              print "$d..." if($PDL::Transform::debug);
              $out->hdr->{"CRPIX$d"} = 1 + ($out->dim($d-1)-1)/2;
              $out->hdr->{"CRVAL$d"} = $midpoint_val->at($d-1);
              $out->hdr->{"NAXIS$d"} = $out->dim($d-1);
              $out->hdr->{"CTYPE$d"} = ( (defined($me->{otype}) ?
                                          $me->{otype}->[$d-1] : "")
                                         || $in->hdr->{"CTYPE$d"}
                                         || "");
              $out->hdr->{"CUNIT$d"} = ( (defined($me->{ounit}) ?
                                          $me->{ounit}->[$d-1] : "")
                                         || $in->hdr->{"CUNIT$d"}
                                         || $in->hdr->{"CTYPE$d"}
                                         || "");
              for my $e(1..$nd) {
                  $out->hdr->{"CD${d}_${e}"} = $mat->at($d-1,$e-1);
                  print "setting CD${d}_${e} to ".$mat->at($d-1,$e-1)."\n" if($PDL::Transform::debug);
              }
          }

          ## Eliminate competing header pointing tags if they exist
          for $k(keys %{$out->hdr}) {
              if( $k =~ m/(^CROTA\d*$)|(^(PC)\d+_\d+[A-Z]?$)|(CDELT\d*$)/ ) {
                  delete $out->hdr->{$k};
              }
          }
      }



    }

  $out->hdrcpy(1);

  ##############################
  # Sandwich the transform between the input and output plane FITS headers.
  unless($nofits) {
      $me = !(t_fits($out,{ignore_rgb=>1})) x $me x $f_in;
  }

  ##############################
  ## Figure out the interpND options
  my $method = _opt($opt,['m','method','Method'],undef);
  my $bound = _opt($opt,['b','bound','boundary','Boundary'],'t');


  ##############################
  ## Rubber meets the road: calculate the inverse transformed points.
  my $ndc = PDL::Basic::ndcoords(@dd);
  my $idx = $me->invert($ndc->double);

  barf "map: Transformation had no inverse\n" unless defined($idx);

  ##############################
  ## Integrate ?  (Jacobian, Gaussian, Hanning)
  my $integrate = ($method =~ m/^[jghJGH]/) if defined($method);

  ##############################
  ## Sampling code:
  ## just transform and interpolate.
  ##  ( Kind of an anticlimax after all that, eh? )
  if(!$integrate) {
    my $a = $in->interpND($idx,{method=>$method, bound=>$bound});
    my $tmp; # work around perl -d "feature"
    ($tmp = $out->slice(":")) .= $a; # trivial slice prevents header overwrite...
    return $out;
  }

  ##############################
  ## Anti-aliasing code:
  ## Condition the input and call the pixelwise C interpolator.
  ##

  barf("PDL::Transform::map: Too many dims in transformation\n")
        if($in->ndims < $idx->ndims-1);

  ####################
  ## Condition the threading -- pixelwise interpolator only threads
  ## in 1 dimension, so squish all thread dimensions into 1, if necessary
  my @iddims = $idx->dims;
  if($in->ndims == $#iddims) {
        $in2 = $in->dummy(-1,1);
  } else {
        $in2 = ( $in
                ->reorder($nd..$in->ndims-1, 0..$nd-1)
                ->clump($in->ndims - $nd)
                ->mv(0,-1)
               );
  }

  ####################
  # Allocate the output array
  my $o2 = PDL->new_from_specification($in2->type,
                                    @iddims[1..$#iddims],
                                    $in2->dim(-1)
                                   );

  ####################
  # Pack boundary string if necessary
  if(defined $bound) {
    if(ref $bound eq 'ARRAY') {
      my ($s,$el);
      foreach $el(@$bound) {
        barf "Illegal boundary value '$el' in range"
          unless( $el =~ m/^([0123fFtTeEpPmM])/ );
        $s .= $1;
      }
      $bound = $s;
    }
    elsif($bound !~ m/^[0123ftepx]+$/  && $bound =~ m/^([0123ftepx])/i ) {
      $bound = $1;
    }
  }

  ####################
  # Get the blur and minimum-sv values
  my $blur  =  _opt($opt,['blur','Blur'],1.0);
  my $svmin =  _opt($opt,['sv','SV'],1.0);
  my $big   =  _opt($opt,['big','Big'],1.0);
  my $flux  =  _opt($opt,['phot','photometry'],0);
  my @idims = $in->dims;

  $flux = ($flux =~ m/^[1fF]/);
  $big = $big * max(pdl(@idims[0..$nd]));
  $blur = $blur->at(0) if(ref $blur);
  $svmin =  $svmin->at(0)  if(ref $svmin);

  my $bv;
  if($PDL::Bad::Status  and $in->badflag){
      $bv = $in->badvalue;
  } else {
      $bv = 0;
  }

  ### The first argument is a dummy to set $GENERIC.
  $idx = double($idx) unless($idx->type == double);
  print "Calling _map_int...\n" if($PDL::Transform::debug);
  &PDL::_map_int( $in2->flat->index(0),
        $in2, $o2, $idx,
        $bound, $method, $big, $blur, $svmin, $flux, $bv);

  my @rdims = (@iddims[1..$#iddims], @idims[$#iddims..$#idims]);
  {
     my $tmp; # work around perl -d "feature"
     ($tmp = $out->slice(":")) .= $o2->reshape(@rdims);
  }
  return $out;
}

+==EOD_map_perlcode==

);


pp_add_exported('unmap');
pp_addpm(<<'+======EOD_unmap======');

######################################################################

=head2 unmap

=for sig

 Signature: (data(); PDL::Transform a; template(); \%opt)

=for usage

  $out_image = $in_image->unmap($t,[<options>],[<template>]);
  $out_image = $t->unmap($in_image,[<options>],[<template>]);

=for ref

Map an image or N-D dataset using the inverse as a coordinate transform.

This convenience function just inverts $t and calls L<map|/map> on
the inverse; everything works the same otherwise.  For convenience, it
is both a PDL method and a PDL::Transform method.

=cut

*PDL::unmap = \&unmap;
sub unmap {
  my($me) = shift;
  my($data) = shift;
  my(@params) = @_;

  if(UNIVERSAL::isa($data,'PDL::Transform') && UNIVERSAL::isa($me,'PDL')) {
      my $a = $data;
      $data = $me;
      $me = $a;
  }

  return $me->inverse->map($data,@params);
}

+======EOD_unmap======

pp_add_exported('t_inverse');
pp_addpm(<<'+======EOD_t_inverse======');

=head2 t_inverse

=for usage

  $t2 = t_inverse($t);
  $t2 = $t->inverse;
  $t2 = $t ** -1;
  $t2 = !$t;

=for ref

Return the inverse of a PDL::Transform.  This just reverses the
func/inv, idim/odim, itype/otype, and iunit/ounit pairs.  Note that
sometimes you end up with a transform that cannot be applied or
mapped, because either the mathematical inverse doesn't exist or the
inverse func isn't implemented.

You can invert a transform by raising it to a negative power, or by
negating it with '!'.

The inverse transform remains connected to the main transform because
they both point to the original parameters hash.  That turns out to be
useful.

=cut

*t_inverse = \&inverse;

sub inverse {
  my($me) = shift;

  unless(defined($me->{inv})) {
    Carp::cluck("PDL::Transform::inverse:  got a transform with no inverse.\n");
    return undef;
  }

  my(%out) = %$me; # force explicit copy of top-level
  my($out) = \%out;

  $out->{inv}  = $me->{func};
  $out->{func} = $me->{inv};

  $out->{idim} = $me->{odim};
  $out->{odim} = $me->{idim};

  $out->{otype} = $me->{itype};
  $out->{itype} = $me->{otype};

  $out->{ounit} = $me->{iunit};
  $out->{iunit} = $me->{ounit};

  $out->{name} = "(inverse ".$me->{name}.")";

  $out->{is_inverse} = !($out->{is_inverse});

  bless $out,(ref $me);
  return $out;
}

+======EOD_t_inverse======

pp_add_exported('t_compose');
pp_addpm(<<'+======EOD_t_compose======');

=head2 t_compose

=for usage

  $f2 = t_compose($f, $g,[...]);
  $f2 = $f->compose($g[,$h,$i,...]);
  $f2 = $f x $g x ...;

=for ref

Function composition: f(g(x)), f(g(h(x))), ...

You can also compose transforms using the overloaded matrix-multiplication
(nee repeat) operator 'x'.

This is accomplished by inserting a splicing code ref into the C<func>
and C<inv> slots.  It combines multiple compositions into a single
list of transforms to be executed in order, fram last to first (in
keeping with standard mathematical notation).  If one of the functions is
itself a composition, it is interpolated into the list rather than left
separate.  Ultimately, linear transformations may also be combined within
the list.

No checking is done that the itype/otype and iunit/ounit fields are
compatible -- that may happen later, or you can implement it yourself
if you like.

=cut

@PDL::Transform::Composition::ISA = ('PDL::Transform');
sub PDL::Transform::Composition::stringify {
  package PDL::Transform::Composition;
  my($me) = shift;
  my($out) = SUPER::stringify $me;
  $out;
}

*t_compose = \&compose;

sub compose {
  local($_);
  my(@funcs) = @_;
  my($me) = PDL::Transform->new;

  # No inputs case: return the identity function
  return $me
    if(!@funcs);

  $me->{name} = "";
  my($f);
  my(@clist);

  for $f(@funcs) {

    $me->{idim} = $f->{idim} if($f->{idim} > $me->{idim});
    $me->{odim} = $f->{odim} if($f->{odim} > $me->{odim});

    if(UNIVERSAL::isa($f,"PDL::Transform::Composition")) {
      if($f->{is_inverse}) {
        for(reverse(@{$f->{params}->{clist}})) {
          push(@clist,$_->inverse);
          $me->{name} .= " o inverse ( ".$_->{name}." )";
        }
      } else {
        for(@{$f->{params}->{clist}}) {
          push(@clist,$_);
          $me->{name} .= " o ".$_->{name};
        }
      }
    } else {  # Not a composition -- just push the transform onto the list.
      push(@clist,$f);
      $me->{name} .= " o ".$f->{name};
    }
  }

  $me->{name}=~ s/^ o //; # Get rid of leading composition mark

  $me->{otype} = $funcs[0]->{otype};
  $me->{ounit} = $funcs[0]->{ounit};

  $me->{itype} = $funcs[-1]->{itype};
  $me->{iunit} = $funcs[-1]->{iunit};

  $me->{params}->{clist} = \@clist;

  $me->{func} = sub {
    my ($data,$p) = @_;
    my ($ip) = $data->is_inplace;
    for my $t ( reverse @{$p->{clist}} ) {
      croak("Error: tried to apply a PDL::Transform with no function inside a composition!\n  offending transform: $t\n")
          unless(defined($t->{func}) and ref($t->{func}) eq 'CODE');
      $data = $t->{func}($ip ? $data->inplace : $data, $t->{params});
    }
    $data->is_inplace(0); # clear inplace flag (avoid core bug with inplace)
    $data;
  };

  $me->{inv} = sub {
    my($data,$p) = @_;
    my($ip) = $data->is_inplace;
    for my $t ( @{$p->{clist}} ) {
      croak("Error: tried to invert a non-invertible PDL::Transform inside a composition!\n  offending transform: $t\n")
          unless(defined($t->{inv}) and ref($t->{inv}) eq 'CODE');
      $data = &{$t->{inv}}($ip ? $data->inplace : $data, $t->{params});
    }
    $data;
  };

  return bless($me,'PDL::Transform::Composition');
}

+======EOD_t_compose======


pp_add_exported('t_wrap');
pp_addpm(<<'+======EOD_t_wrap======');

=head2 t_wrap

=for usage

  $g1fg = $f->wrap($g);
  $g1fg = t_wrap($f,$g);

=for ref

Shift a transform into a different space by 'wrapping' it with a second.

This is just a convenience function for two
L<t_compose|/t_compose> calls. C<< $a->wrap($b) >> is the same as
C<(!$b) x $a x $b>: the resulting transform first hits the data with
$b, then with $a, then with the inverse of $b.

For example, to shift the origin of rotation, do this:

  $im = rfits('m51.fits');
  $tf = t_fits($im);
  $tr = t_linear({rot=>30});
  $im1 = $tr->map($tr);               # Rotate around pixel origin
  $im2 = $tr->map($tr->wrap($tf));    # Rotate round FITS scientific origin

=cut

*t_wrap = \&wrap;

sub wrap {
  my($f) = shift;
  my($g) = shift;

  return $g->inverse->compose($f,$g);
}



######################################################################

# Composition operator -- handles 'x'.
sub _compose_op {
    my($a,$b,$c) = @_;
    $c ? compose($b,$a) : compose($a,$b);
}

# Raise-to-power operator -- handles '**'.

sub _pow_op {
    my($a,$b,$c) = @_;

    barf("%s", "Can't raise anything to the power of a transform")
        if($c || UNIVERSAL::isa($b,'PDL::Transform')) ;

    $a = $a->inverse
        if($b < 0);

    return $a if(abs($b) == 1);
    return new PDL::Transform if(abs($b) == 0);

    my(@l);
    for my $i(1..abs($b)) {
        push(@l,$a);
    }

    t_compose(@l);
}

+======EOD_t_wrap======


pp_add_exported('t_identity');
pp_addpm(<<'+======EOD_t_identity======');

=head2 t_identity

=for usage

  my $xform = t_identity
  my $xform = new PDL::Transform;

=for ref

Generic constructor generates the identity transform.

This constructor really is trivial -- it is mainly used by the other transform
constructors.  It takes no parameters and returns the identity transform.

=cut

sub _identity { return shift; }
sub t_identity { new PDL::Transform(@_) };

sub new {
  my($class) = shift;
  my $me = {name=>'identity',
            idim => 0,
            odim => 0,
            func=>\&PDL::Transform::_identity,
            inv=>\&PDL::Transform::_identity,
            params=>{}
          };

  return bless $me,$class;
}

+======EOD_t_identity======


pp_add_exported('t_lookup');
pp_addpm(<<'+======EOD_t_lookup======');

=head2 t_lookup

=for usage

  $f = t_lookup($lookup, {<options>});

=for ref

Transform by lookup into an explicit table.

You specify an N+1-D PDL that is interpreted as an N-D lookup table of
column vectors (vector index comes last).  The last dimension has
order equal to the output dimensionality of the transform.

For added flexibility in data space, You can specify pre-lookup linear
scaling and offset of the data.  Of course you can specify the
interpolation method to be used.  The linear scaling stuff is a little
primitive; if you want more, try composing the linear transform with
this one.

The prescribed values in the lookup table are treated as
pixel-centered: that is, if your input array has N elements per row
then valid data exist between the locations (-0.5) and (N-0.5) in
lookup pixel space, because the pixels (which are numbered from 0 to
N-1) are centered on their locations.

Lookup is done using L<interpND|PDL::Primitive/interpnd>, so the boundary conditions
and threading behaviour follow from that.

The indexed-over dimensions come first in the table, followed by a
single dimension containing the column vector to be output for each
set of other dimensions -- ie to output 2-vectors from 2 input
parameters, each of which can range from 0 to 49, you want an index
that has dimension list (50,50,2).  For the identity lookup table
you could use  C<cat(xvals(50,50),yvals(50,50))>.

If you want to output a single value per input vector, you still need
that last index threading dimension -- if necessary, use C<dummy(-1,1)>.

The lookup index scaling is: out = lookup[ (scale * data) + offset ].

A simplistic table inversion routine is included.  This means that
you can (for example) use the C<map> method with C<t_lookup> transformations.
But the table inversion is exceedingly slow, and not practical for tables
larger than about 100x100.  The inversion table is calculated in its
entirety the first time it is needed, and then cached until the object is
destroyed.

Options are listed below; there are several synonyms for each.

=over 3

=item s, scale, Scale

(default 1.0) Specifies the linear amount of scaling to be done before
lookup.  You can feed in a scalar or an N-vector; other values may cause
trouble.  If you want to save space in your table, then specify smaller
scale numbers.

=item o, offset, Offset

(default 0.0) Specifies the linear amount of offset before lookup.
This is only a scalar, because it is intended to let you switch to
corner-centered coordinates if you want to (just feed in o=-0.25).

=item b, bound, boundary, Boundary

Boundary condition to be fed to L<interpND|PDL::Primitive/interpND>

=item m, method, Method

Interpolation method to be fed to L<interpND|PDL::Primitive/interpND>

=back

EXAMPLE

To scale logarithmically the Y axis of m51, try:

  $a = float rfits('m51.fits');
  $lookup = xvals(128,128) -> cat( 10**(yvals(128,128)/50) * 256/10**2.55 );
  $t = t_lookup($lookup);
  $b = $t->map($a);

To do the same thing but with a smaller lookup table, try:

  $lookup = 16 * xvals(17,17)->cat(10**(yvals(17,17)/(100/16)) * 16/10**2.55);
  $t = t_lookup($lookup,{scale=>1/16.0});
  $b = $t->map($a);

(Notice that, although the lookup table coordinates are is divided by 16,
it is a 17x17 -- so linear interpolation works right to the edge of the original
domain.)

NOTES

Inverses are not yet implemented -- the best way to do it might be by
judicious use of map() on the forward transformation.

the type/unit fields are ignored.

=cut

sub t_lookup {
  my($class) = 'PDL::Transform';
  my($source)= shift;
  my($o) = shift;

  if(!defined($o) && ((ref $source) eq 'HASH')) {
    Carp::cluck("lookup transform called as sub not method; using 'PDL::Transform' as class...\n");
    $o = $source;
    $source = $class;
    $class = "PDL::Transform";
  }

  $o = {} unless(ref $o eq 'HASH');

  my($me) = PDL::Transform::new($class);

  my($bound) = _opt($o,['b','bound','boundary','Boundary']);
  my($method)= _opt($o,['m','meth','method','Method']);

  $me->{idim} = $source->ndims - 1;
  $me->{odim} = $source->dim($source->ndims-1);

  $me->{params} = {
      table => $source,
      scale =>  _opt($o,['s','scale','Scale'],1.0),
      offset => _opt($o,['o','off','offset','Offset'],0.0),
      interpND_opt => {
        method => $method,
        bound =>  $bound,
        bad   => _opt($o,['bad'],0)
      }
    };


   my $lookup_func = sub {
     my($data,$p,$table,$scale,$offset) = @_;

    $data = pdl($data)
      unless ((ref $data) && (UNIVERSAL::isa($data,'PDL')));
      $main::foo = $data;

    if($data->dim(0) > $me->{idim}) {
      barf("Too many dims (".$data->dim(0).") for your table (".$me->{idim}.")\n");
    };

    my($a)= ($table
             ->interpND(float($data) * $scale + $offset,
                        $p->{interpND_opt}
                        )
             );


    # Put the index dimension (and threaded indices) back at the front of
    # the dimension list.
    my($dnd) = $data->ndims - 1;
    return ($a -> ndims > $data->ndims - 1) ?
      ($a->reorder( $dnd..($dnd + $table->ndims - $data->dim(0)-1)
                    , 0..$data->ndims-2
                    )
       ) : $a;
  };

  $me->{func} = sub {my($data,$p) = @_;  &$lookup_func($data,$p,$p->{table},$p->{scale},$p->{offset})};

  #######
  ## Lazy inverse -- find it if and only if we need it...
  $me->{inv} = sub {
      my $data = shift;
      my $p = shift;
      if(!defined($p->{'itable'})) {
        if($me->{idim} != $me->{odim}) {
         barf("t_lookup: can't calculate an inverse of a projection operation! (idim != odim)");
        }
       print "t_lookup: Warning, table inversion is only weakly supported.  \n   I'll try to invert it using a pretty boneheaded algorithm...\n  (If it takes too long, consider writing a faster algorithm!)\n   Calculating inverse table (will be cached)...\n" if($PDL::verbose || $PDL::debug || $PDL::Transform::debug);
        my $itable = zeroes($p->{table});
        my $minvals = $p->{table}->clump($me->{idim})->minimum;
        my $maxvals = $p->{table}->clump($me->{idim})->maximum;

        # Scale so that the range runs from 0 through the top pixel in the table
        my $scale = (  pdl(  $itable->dims  )->slice("0:-2")-1  ) /
                    (($maxvals - $minvals)+ (($maxvals-$minvals) == 0));
        my $offset = - ($minvals * $scale);

        $p->{iscale} = $scale;
        $p->{ioffset} = $offset;

        my $enl_scale = $p->{'enl_scale'} || 10;
        my $smallcoords = ndcoords((pdl($enl_scale * 2 + 1)->at(0)) x $me->{idim})/ $enl_scale - 1;

        # $oloop runs over (point, index) for all points in the output table, in
        # $p->{table} output space
        $oloop = ndcoords($itable->mv(-1,0)->slice("(0)"))->
            double->
            mv(0,-1)->
            clump($itable->ndims-1);  # oloop: (pixel, index)
        {
            my $tmp; # work around perl -d "feature"
            ($tmp = $oloop->mv(-1,0)) -= $offset;
            ($tmp = $oloop->mv(-1,0)) /= $scale;
        }

        # The Right Thing to do here is to take the outer product of $itable and $otable, then collapse
        # to find minimum distance.  But memory demands for that would be HUGE.  Instead we do an
        # elementwise calculation.

        print "t_lookup: inverting ".$oloop->dim(0)." points...\n" if($PDL::verbose || $PDL::debug || $PDL::Transform::debug);
        my $pt = $p->{table}->mv(-1,0); # pt runs (index, x,y,...)

        my $itable_flattened = zeroes($oloop);

        for $i(0..$oloop->dim(0)-1) {

            my $olp = $oloop->slice("($i)");                # olp runs (index)
            my $diff = ($pt - $olp);                 # diff runs (index, x, y, ...)
            my $r2 = ($diff * $diff)->sumover;       # r2 runs (x,y,...)
            my $c = whichND($r2==$r2->min)->slice(":,(0)"); # c runs (index)

            # Now zero in on the neighborhood around the point of closest approach.
            my $neighborhood = $p->{table}->interpND($c + $smallcoords,{method=>'linear',bound=>'t'})->
                     mv(-1,0); # neighborhood runs (index, dx, dy,...)
            $diff = $neighborhood - $olp;        # diff runs (index, dx, dy, ...)
            $r2 = ($diff * $diff)->sumover;      # r2 runs (dx,dy,...)
            my $dc = $smallcoords->mv(0,-1)->indexND(0+whichND($r2==$r2->min)->slice(":,(0)"));


            my $coord = $c + $dc;
            # At last, we've found the best-fit to an enl_scale'th of an input-table pixel.
            # Back it out to input-science coordinates, and stuff it in the inverse table.
            my $tmp; # work around perl -d "feature"
            ($tmp = $itable_flattened->slice("($i)")) .= $coord;

            print " $i..." if( ($i%1000==0) && ( $PDL::verbose || $PDL::debug || $PDL::Transform::debug));
        }

        {
            my $tmp; # work around perl -d "feature"
            ($tmp = $itable->clump($itable->ndims-1)) .= $itable_flattened;
            ($tmp = $itable->mv(-1,0)) -= $p->{offset};
            ($tmp = $itable->mv(-1,0)) /= $p->{scale};
        }

        $p->{itable} = $itable;
      }
      &$lookup_func($data,$p, $p->{itable},$p->{iscale},$p->{ioffset}) ;
    };


  $me->{name} = 'Lookup';

  return $me;
}

+======EOD_t_lookup======

pp_add_exported('t_linear');
pp_addpm(<<'+======EOD_t_linear======');

=head2 t_linear

=for usage

$f = t_linear({options});

=for ref

Linear (affine) transformations with optional offset

t_linear implements simple matrix multiplication with offset,
also known as the affine transformations.

You specify the linear transformation with pre-offset, a mixing
matrix, and a post-offset.  That overspecifies the transformation, so
you can choose your favorite method to specify the transform you want.
The inverse transform is automagically generated, provided that it
actually exists (the transform matrix is invertible).  Otherwise, the
inverse transform just croaks.

Extra dimensions in the input vector are ignored, so if you pass a
3xN vector into a 3-D linear transformation, the final dimension is passed
through unchanged.

The options you can usefully pass in are:

=over 3

=item s, scale, Scale

A scaling scalar (heh), vector, or matrix.  If you specify a vector
it is treated as a diagonal matrix (for convenience).  It gets
left-multiplied with the transformation matrix you specify (or the
identity), so that if you specify both a scale and a matrix the
scaling is done after the rotation or skewing or whatever.

=item r, rot, rota, rotation, Rotation

A rotation angle in degrees -- useful for 2-D and 3-D data only.  If
you pass in a scalar, it specifies a rotation from the 0th axis toward
the 1st axis.  If you pass in a 3-vector as either a PDL or an array
ref (as in "rot=>[3,4,5]"), then it is treated as a set of Euler
angles in three dimensions, and a rotation matrix is generated that
does the following, in order:

=over 3

=item * Rotate by rot->(2) degrees from 0th to 1st axis

=item * Rotate by rot->(1) degrees from the 2nd to the 0th axis

=item * Rotate by rot->(0) degrees from the 1st to the 2nd axis

=back

The rotation matrix is left-multiplied with the transformation matrix
you specify, so that if you specify both rotation and a general matrix
the rotation happens after the more general operation -- though that is
deprecated.

Of course, you can duplicate this functionality -- and get more
general -- by generating your own rotation matrix and feeding it in
with the C<matrix> option.

=item m, matrix, Matrix

The transformation matrix.  It does not even have to be square, if you want
to change the dimensionality of your input.  If it is invertible (note:
must be square for that), then you automagically get an inverse transform too.

=item pre, preoffset, offset, Offset

The vector to be added to the data before they get multiplied by the matrix
(equivalent of CRVAL in FITS, if you are converting from scientific to
pixel units).

=item post, postoffset, shift, Shift

The vector to be added to the data after it gets multiplied by the matrix
(equivalent of CRPIX-1 in FITS, if youre converting from scientific to pixel
units).

=item d, dim, dims, Dims

Most of the time it is obvious how many dimensions you want to deal
with: if you supply a matrix, it defines the transformation; if you
input offset vectors in the C<pre> and C<post> options, those define
the number of dimensions.  But if you only supply scalars, there is no way
to tell and the default number of dimensions is 2.  This provides a way
to do, e.g., 3-D scaling: just set C<{s=><scale-factor>, dims=>3}> and
you are on your way.

=back

NOTES

the type/unit fields are currently ignored by t_linear.

=cut

@PDL::Transform::Linear::ISA = ('PDL::Transform');

sub t_linear { new PDL::Transform::Linear(@_); }

sub PDL::Transform::Linear::new {
  my($class) = shift;
  my($o) = $_[0];
  pop @_ if (($#_ % 2 ==0) && !defined($_[-1]));
  #suppresses a warning if @_ has an odd number of elements and the
  #last is undef

  if(!(ref $o)) {
    $o = {@_};
  }

  my($me) = PDL::Transform::new($class);

  $me->{name} = "linear";

  $me->{params}->{pre} = _opt($o,['pre','Pre','preoffset','offset',
                                  'Offset','PreOffset','Preoffset'],0);
  $me->{params}->{pre} = pdl($me->{params}->{pre})
    if(defined $me->{params}->{pre});

  $me->{params}->{post} = _opt($o,['post','Post','postoffset','PostOffset',
                                   'shift','Shift'],0);
  $me->{params}->{post} = pdl($me->{params}->{post})
    if(defined $me->{params}->{post});

  $me->{params}->{matrix} = _opt($o,['m','matrix','Matrix','mat','Mat']);
  $me->{params}->{matrix} = pdl($me->{params}->{matrix})
    if(defined $me->{params}->{matrix});

  $me->{params}->{rot} = _opt($o,['r','rot','rota','rotation','Rotation']);
  $me->{params}->{rot} = 0 unless defined($me->{params}->{rot});
  $me->{params}->{rot} = pdl($me->{params}->{rot});

  my $o_dims = _opt($o,['d','dim','dims','Dims']);
  $o_dims = pdl($o_dims)
    if defined($o_dims);

  my $scale  = _opt($o,['s','scale','Scale']);
  $scale = pdl($scale)
    if defined($scale);

  # Figure out the number of dimensions to transform, and,
  # if necessary, generate a new matrix.

  if(defined($me->{params}->{matrix})) {
    my $mat = $me->{params}->{matrix} = $me->{params}->{matrix}->slice(":,:");
    $me->{idim} = $mat->dim(0);
    $me->{odim} = $mat->dim(1);

  } else {
    if(defined($me->{params}->{rot}) &&
        UNIVERSAL::isa($me->{params}->{rot},'PDL')) {
          $me->{idim} = $me->{odim} = 2 if($me->{params}->{rot}->nelem == 1);
          $me->{idim} = $me->{odim} = 3 if($me->{params}->{rot}->nelem == 3);
    }

    if(defined($scale) &&
       UNIVERSAL::isa($scale,'PDL') &&
       $scale->getndims > 0) {
      $me->{idim} = $me->{odim} = $scale->dim(0);
      $me->{odim} = $scale->dim(0);

    } elsif(defined($me->{params}->{pre}) &&
            UNIVERSAL::isa($me->{params}->{pre},'PDL') &&
            $me->{params}->{pre}->getndims > 0) {
      $me->{idim} = $me->{odim} = $me->{params}->{pre}->dim(0);

    } elsif(defined($me->{params}->{post}) &&
            UNIVERSAL::isa($me->{params}->{post},'PDL') &&
            $me->{params}->{post}->getndims > 0) {
      $me->{idim} = $me->{odim} = $me->{params}->{post}->dim(0);
    } elsif(defined($o_dims)) {
      $me->{idim} = $me->{odim} = $o_dims;
    } else {
      print "PDL::Transform::Linear: assuming 2-D transform (set dims option to change)\n" if($PDL::Transform::debug);
      $me->{idim} = $me->{odim} = 2;
    }

    $me->{params}->{matrix} = PDL->zeroes($me->{idim},$me->{odim});
    my $tmp; # work around perl -d "feature"
    ($tmp = $me->{params}->{matrix}->diagonal(0,1)) .= 1;

  }

  ### Handle rotation option
  my $rot = $me->{params}->{rot};
  if(defined($rot)) {
    # Subrotation closure -- rotates from axis $d->(0) --> $d->(1).
    my $subrot = sub {
                       my($d,$angle,$m)=@_;
                       my($i) = identity($m->dim(0));
                       my($subm) = $i->dice($d,$d);

                       $angle = $angle->at(0)
                         if(UNIVERSAL::isa($angle,'PDL'));

                       my($a) = $angle * $DEG2RAD;
                       $subm .= $subm x pdl([cos($a),-sin($a)],[sin($a),cos($a)]);
                       $m .= $m x $i;
                     };

    if(UNIVERSAL::isa($rot,'PDL') && $rot->nelem > 1) {
      if($rot->ndims == 2) {
        $me->{params}->{matrix} x= $rot;
      } elsif($rot->nelem == 3) {
        my $rm = identity(3);

        # Do these in reverse order to make it more like
        # function composition!
        &$subrot(pdl(0,1),$rot->at(2),$rm);
        &$subrot(pdl(2,0),$rot->at(1),$rm);
        &$subrot(pdl(1,2),$rot->at(0),$rm);

        $me->{params}->{matrix} .= $me->{params}->{matrix} x $rm;
      } else {
        barf("PDL::Transform::Linear: Got a strange rot option -- giving up.\n");
      }
    } else {
        if($rot != 0  and  $me->{params}->{matrix}->dim(0)>1) {
          &$subrot(pdl(0,1),$rot,$me->{params}->{matrix});
        }
    }
  }


  #
  # Apply scaling
  #
  $me->{params}->{matrix} = $me->{params}->{matrix}->slice(":,:");
  my $tmp; # work around perl -d "feature"
  ($tmp = $me->{params}->{matrix}->diagonal(0,1)) *= $scale
    if defined($scale);

  #
  # Check for an inverse and apply it if possible
  #
  my($o2);
  if($me->{params}->{matrix}->det($o2 = {lu=>undef})) {
    $me->{params}->{inverse} = $me->{params}->{matrix}->inv($o2);
  } else {
    delete $me->{params}->{inverse};
  }

  $me->{params}->{idim} = $me->{idim};
  $me->{params}->{odim} = $me->{odim};


  ##############################
  # The meat -- just shift, matrix-multiply, and shift again.
  $me->{func} = sub {
    my($in,$opt) = @_;

    my($d) = $opt->{matrix}->dim(0)-1;

    barf("Linear transform: transform is $d-D; data only ".($in->dim(0))."\n")
        if($in->dim(0) < $d);

    my($a) = $in->slice("0:$d")->copy + $opt->{pre};
    my($out) = $in->is_inplace ? $in : $in->copy;

    my $tmp; # work around perl -d "feature"
    ($tmp = $out->slice("0:$d")) .= $a x $opt->{matrix} + $opt->{post};

    return $out;
  };


  $me->{inv} = (defined $me->{params}->{inverse}) ? sub {
    my($in,$opt) = @_;

    my($d) = $opt->{inverse}->dim(0)-1;
    barf("Linear transform: transform is $d-D; data only ".($in->dim(0))."\n")
        if($in->dim(0) < $d);

    my($a) = $in->slice("0:$d")->copy - $opt->{post};
    my($out) = $in->is_inplace ? $in : $in->copy;

    my $tmp; # work around perl -d "feature"
    ($tmp = $out->slice("0:$d")) .= $a x $opt->{inverse} - $opt->{pre};

    $out;
  } : undef;

  return $me;
}

sub PDL::Transform::Linear::stringify {
  package PDL::Transform::Linear;
  my($me) = shift;  my($out) = SUPER::stringify $me;
  my $mp = $me->{params};

  if(!($me->{is_inverse})){
    $out .= "Pre-add: ".($mp->{pre})."\n"
      if(defined $mp->{pre});

    $out .= "Post-add: ".($mp->{post})."\n"
      if(defined $mp->{post});

    $out .= "Forward matrix:".($mp->{matrix})
      if(defined $mp->{matrix});

    $out .= "Inverse matrix:".($mp->{inverse})
      if(defined $mp->{inverse});
  } else {
    $out .= "Pre-add: ".(-$mp->{post})."\n"
      if(defined $mp->{post});

    $out .= "Post-add: ".(-$mp->{pre})."\n"
      if(defined $mp->{pre});

    $out .= "Forward matrix:".($mp->{inverse})
      if(defined $mp->{inverse});

    $out .= "Inverse matrix:".($mp->{matrix})
      if(defined $mp->{matrix});
  }

  $out =~ s/\n/\n  /go;
  $out;
}

+======EOD_t_linear======


pp_add_exported('t_scale');
pp_addpm(<<'+======EOD_t_scale======');

=head2 t_scale

=for usage

  $f = t_scale(<scale>)

=for ref

Convenience interface to L<t_linear|/t_linear>.

t_scale produces a transform that scales around the origin by a fixed
amount.  It acts exactly the same as C<t_linear(Scale=>\<scale\>)>.

=cut

sub t_scale {
    my($scale) = shift;
    my($b) = shift;
    return t_linear(scale=>$scale,%{$b})
        if(ref $b eq 'HASH');
    t_linear(Scale=>$scale,$b,@_);
}

+======EOD_t_scale======

pp_add_exported('t_offset ');
pp_addpm(<<'+======EOD_t_offset ======');

=head2 t_offset

=for usage

  $f = t_offset(<shift>)

=for ref

Convenience interface to L<t_linear|/t_linear>.

t_offset produces a transform that shifts the origin to a new location.
It acts exactly the same as C<t_linear(Pre=>\<shift\>)>.

=cut

sub t_offset {
    my($pre) = shift;
    my($b) = shift;
    return t_linear(pre=>$pre,%{$b})
        if(ref $b eq 'HASH');

    t_linear(pre=>$pre,$b,@_);
}

+======EOD_t_offset ======

pp_add_exported('t_rot');
pp_addpm(<<'+======EOD_t_rot======');

=head2 t_rot

=for usage

  $f = t_rot(<rotation-in-degrees>)

=for ref

Convenience interface to L<t_linear|/t_linear>.

t_rot produces a rotation transform in 2-D (scalar), 3-D (3-vector), or
N-D (matrix).  It acts exactly the same as C<t_linear(Rot=>\<shift\>)>.

=cut

*t_rot = \&t_rotate;
sub t_rotate    {
    my $rot = shift;
    my($b) = shift;
    return t_linear(rot=>$rot,%{$b})
        if(ref $b eq 'HASH');

    t_linear(rot=>$rot,$b,@_);
}

+======EOD_t_rot======



pp_add_exported('t_fits');
pp_addpm(<<'+======EOD_t_fits======');

=head2 t_fits

=for usage

  $f = t_fits($fits,[option]);

=for ref

FITS pixel-to-scientific transformation with inverse

You feed in a hash ref or a PDL with one of those as a header, and you
get back a transform that converts 0-originated, pixel-centered
coordinates into scientific coordinates via the transformation in the
FITS header.  For most FITS headers, the transform is reversible, so
applying the inverse goes the other way.  This is just a convenience
subclass of PDL::Transform::Linear, but with unit/type support
using the FITS header you supply.

For now, this transform is rather limited -- it really ought to
accept units differences and stuff like that, but they are just
ignored for now.  Probably that would require putting units into
the whole transform framework.

This transform implements the linear transform part of the WCS FITS
standard outlined in Greisen & Calabata 2002 (A&A in press; find it at
"http://arxiv.org/abs/astro-ph/0207407").

As a special case, you can pass in the boolean option "ignore_rgb"
(default 0), and if you pass in a 3-D FITS header in which the last
dimension has exactly 3 elements, it will be ignored in the output
transformation.  That turns out to be handy for handling rgb images.

=cut

sub t_fits {
  my($class) = 'PDL::Transform::Linear';
  my($hdr) = shift;
  my($opt) = shift;

  if(ref $opt ne 'HASH') {
    $opt = defined $opt ? {$opt,@_} : {} ;
  }

  $hdr = $hdr->gethdr
    if(defined $hdr && UNIVERSAL::isa($hdr,'PDL'));

  croak('PDL::Transform::FITS::new requires a FITS header hash\n')
    if(!defined $hdr || ref $hdr ne 'HASH' || !defined($hdr->{NAXIS}));

  my($n) = $hdr->{NAXIS}; $n = $n->at(0) if(UNIVERSAL::isa($n,'PDL'));

  $n = 2
    if($opt->{ignore_rgb} && $n==3 && $hdr->{NAXIS3} == 3);

  my($matrix) = PDL->zeroes($hdr->{NAXIS},$hdr->{NAXIS});
  my($pre) = PDL->zeroes($n);
  my($post) = PDL->zeroes($n);

  ##############################
  # Scaling: Use CDi_j formalism if present; otherwise use the
  # older PCi_j + CDELTi formalism.

  my(@hgrab);

  if(@hgrab = grep(m/^CD\d{1,3}_\d{1,3}$/,keys %$hdr)) {   # assignment
    #
    # CDi_j formalism
    #
    for my $h(@hgrab) {
      $h =~ m/CD(\d{1,3})_(\d{1,3})/;  # Should always match
      my $tmp; # work around perl -d "feature"
      ($tmp = $matrix->slice("(".($1-1)."),(".($2-1).")")) .= $hdr->{$h};
    }
    print "PDL::Transform::FITS: Detected CDi_j matrix: \n",$matrix,"\n"
      if($PDL::Transform::debug);

  } else {

    #
    # PCi_j + CDELTi formalism
    # If PCi_j aren't present, and N=2, then try using CROTA or
    # CROTA2 to generate a rotation matrix instea.
    #

    my($cdm) = PDL->zeroes($n,$n);
    my($cd) = $cdm->diagonal(0,1);

    my($cpm) = PDL->zeroes($n,$n);
    my $tmp; # work around perl -d "feature"
    ($tmp = $cpm->diagonal(0,1)) .= 1;     # PC: diagonal defaults to unity
    $cd .= 1;


    if( @hgrab = grep(m/^PC\d{1,3}_\d{1,3}$/,keys %$hdr) ) {  # assignment

      for my $h(@hgrab) {
        $h =~ m/PC(\d{1,3})_(\d{1,3})$/ || die "t_fits - match failed! This should never happen!";
        my $tmp; # work around perl -d "feature"
        ($tmp = $cpm->slice("(".($1-1)."),(".($2-1).")")) .= $hdr->{$h};
      }
      print "PDL::Transform::FITS: Detected PCi_j matrix: \n",$cpm,"\n"
        if($PDL::Transform::debug && @hgrab);

    } elsif($n==2 && ( defined $hdr->{CROTA} || defined $hdr->{CROTA1} || defined $hdr->{CROTA2}) ) {

        ## CROTA is deprecated; CROTA1 was used for a while but is unofficial;
        ## CROTA2 is encouraged instead.
      my $cr;
      $cr = $hdr->{CROTA2} unless defined $cr;
      $cr = $hdr->{CROTA} unless defined $cr;
      $cr = $hdr->{CROTA1} unless defined $cr;

      $cr *= $DEG2RAD;
        # Rotation matrix rotates counterclockwise to get from sci to pixel coords
        # (detector has been rotated ccw, according to FITS standard)
      $cpm .= pdl( [cos($cr), sin($cr)],[-sin($cr),cos($cr)] );

    }

    for my $i(1..$n) {
      my $tmp; # work around perl -d "feature"
      ($tmp = $cd->slice("(".($i-1).")")) .= $hdr->{"CDELT$i"};
    }
#If there are no CDELTs, then we assume they are all 1.0,
#as in PDL::Graphics::PGPLOT::Window::_FITS_tr.
    $cd+=1 if (all($cd==0));

    $matrix = $cdm x $cpm;
  }

  my($i1) = 0;
  for my $i(1..$n) {
    my $tmp; # work around perl -d "feature"
    ($tmp = $pre->slice("($i1)"))  .= 1 - $hdr->{"CRPIX$i"};
    ($tmp = $post->slice("($i1)")) .= $hdr->{"CRVAL$i"};
    $i1++;
  }

  my($me) = PDL::Transform::Linear::new($class,
                                        {'pre'=>$pre,
                                         'post'=>$post,
                                         'matrix'=>$matrix
                                         });

  $me->{name} = 'FITS';

  my (@otype,@ounit,@itype,@iunit);
  our (@names) = ('X','Y','Z') unless @names;

  for my $i(1..$hdr->{NAXIS}) {
    push(@otype,$hdr->{"CTYPE$i"});
    push(@ounit,$hdr->{"CUNIT$i"});
    push(@itype,"Image ". ( ($i-1<=$#names) ? $names[$i-1] : "${i}th dim" ));
    push(@iunit,"Pixels");
  }

  $me->{otype} = \@otype;
  $me->{itype} = \@itype;
  $me->{ounit} = \@ounit;
  $me->{iunit} = \@iunit;

  # Check for nonlinear projection...
#  if($hdr->{CTYPE1} =~ m/(\w\w\w\w)\-(\w\w\w)/) {
#      print "Nonlinear transformation found... ignoring nonlinear part...\n";
#  }

  return $me;


}

+======EOD_t_fits======





pp_add_exported('t_code ');
pp_addpm(<<'+======EOD_t_code ======');

=head2 t_code

=for usage

  $f = t_code(<func>,[<inv>],[options]);

=for ref

Transform implementing arbitrary perl code.

This is a way of getting quick-and-dirty new transforms.  You pass in
anonymous (or otherwise) code refs pointing to subroutines that
implement the forward and, optionally, inverse transforms.  The
subroutines should accept a data PDL followed by a parameter hash ref,
and return the transformed data PDL.  The parameter hash ref can be
set via the options, if you want to.

Options that are accepted are:

=over 3

=item p,params

The parameter hash that will be passed back to your code (defaults to the
empty hash).

=item n,name

The name of the transform (defaults to "code").

=item i, idim (default 2)

The number of input dimensions (additional ones should be passed through
unchanged)

=item o, odim (default 2)

The number of output dimensions

=item itype

The type of the input dimensions, in an array ref (optional and advisiory)

=item otype

The type of the output dimension, in an array ref (optional and advisory)

=item iunit

The units that are expected for the input dimensions (optional and advisory)

=item ounit

The units that are returned in the output (optional and advisory).

=back

The code variables are executable perl code, either as a code ref or
as a string that will be eval'ed to produce code refs.  If you pass in
a string, it gets eval'ed at call time to get a code ref.  If it compiles
OK but does not return a code ref, then it gets re-evaluated with "sub {
... }" wrapped around it, to get a code ref.

Note that code callbacks like this can be used to do really weird
things and generate equally weird results -- caveat scriptor!

=cut

sub t_code {
  my($class) = 'PDL::Transform';
  my($func, $inv, $o) = @_;
  if(ref $inv eq 'HASH') {
    $o = $inv;
    $inv = undef;
  }

  my($me) = PDL::Transform::new($class);
  $me->{name} = _opt($o,['n','name','Name']) || "code";
  $me->{func} = $func;
  $me->{inv} = $inv;
  $me->{params} = _opt($o,['p','params','Params']) || {};
  $me->{idim} = _opt($o,['i','idim']) || 2;
  $me->{odim} = _opt($o,['o','odim']) || 2;
  $me->{itype} = _opt($o,['itype']) || [];
  $me->{otype} = _opt($o,['otype']) || [];
  $me->{iunit} = _opt($o,['iunit']) || [];
  $me->{ounit} = _opt($o,['ounit']) || [];

  $me;
}

+======EOD_t_code ======



pp_add_exported('t_cylindrical');
pp_add_exported('t_radial');
pp_addpm(<<'+======EOD_t_cylindrical======');

=head2 t_cylindrical

C<t_cylindrical> is an alias for C<t_radial>

=head2 t_radial

=for usage

  $f = t_radial(<options>);

=for ref

Convert Cartesian to radial/cylindrical coordinates.  (2-D/3-D; with inverse)

Converts 2-D Cartesian to radial (theta,r) coordinates.  You can choose
direct or conformal conversion.  Direct conversion preserves radial
distance from the origin; conformal conversion preserves local angles,
so that each small-enough part of the image only appears to be scaled
and rotated, not stretched.  Conformal conversion puts the radius on a
logarithmic scale, so that scaling of the original image plane is
equivalent to a simple offset of the transformed image plane.

If you use three or more dimensions, the higher dimensions are ignored,
yielding a conversion from Cartesian to cylindrical coordinates, which
is why there are two aliases for the same transform.  If you use higher
dimensionality than 2, you must manually specify the origin or you will
get dimension mismatch errors when you apply the transform.

Theta runs B<clockwise> instead of the more usual counterclockwise; that is
to preserve the mirror sense of small structures.

OPTIONS:

=over 3

=item d, direct, Direct

Generate (theta,r) coordinates out (this is the default); incompatible
with Conformal.  Theta is in radians, and the radial coordinate is
in the units of distance in the input plane.

=item r0, c, conformal, Conformal

If defined, this floating-point value causes t_radial to generate
(theta, ln(r/r0)) coordinates out.  Theta is in radians, and the
radial coordinate varies by 1 for each e-folding of the r0-scaled
distance from the input origin.  The logarithmic scaling is useful for
viewing both large and small things at the same time, and for keeping
shapes of small things preserved in the image.

=item o, origin, Origin [default (0,0,0)]

This is the origin of the expansion.  Pass in a PDL or an array ref.

=item u, unit, Unit [default 'radians']

This is the angular unit to be used for the azimuth.

=back

EXAMPLES

These examples do transformations back into the same size image as they
started from; by suitable use of the "transform" option to
L<unmap|/unmap> you can send them to any size array you like.

Examine radial structure in M51:
Here, we scale the output to stretch 2*pi radians out to the
full image width in the horizontal direction, and to stretch 1 radius out
to a diameter in the vertical direction.

  $a = rfits('m51.fits');
  $ts = t_linear(s => [250/2.0/3.14159, 2]); # Scale to fill orig. image
  $tu = t_radial(o => [130,130]);            # Expand around galactic core
  $b = $a->map($ts x $tu);

Examine radial structure in M51 (conformal):
Here, we scale the output to stretch 2*pi radians out to the full image width
in the horizontal direction, and scale the vertical direction by the exact
same amount to preserve conformality of the operation.  Notice that
each piece of the image looks "natural" -- only scaled and not stretched.

  $a = rfits('m51.fits')
  $ts = t_linear(s=> 250/2.0/3.14159);  # Note scalar (heh) scale.
  $tu = t_radial(o=> [130,130], r0=>5); # 5 pix. radius -> bottom of image
  $b = $ts->compose($tu)->unmap($a);


=cut

*t_cylindrical = \&t_radial;
sub t_radial {
  my($class) = 'PDL::Transform';
  my($o) = $_[0];
  if(ref $o ne 'HASH') {
    $o = { @_ };
  }

  my($me) = PDL::Transform::new($class);

  $me->{params}->{origin} = _opt($o,['o','origin','Origin']);
  $me->{params}->{origin} = pdl(0,0)
    unless defined($me->{params}->{origin});
  $me->{params}->{origin} = PDL->pdl($me->{params}->{origin});


  $me->{params}->{r0} = _opt($o,['r0','R0','c','conformal','Conformal']);
  $me->{params}->{origin} = PDL->pdl($me->{params}->{origin});

  $me->{params}->{u} = _opt($o,['u','unit','Unit'],'radians');
  ### Replace this kludge with a units call
  $me->{params}->{angunit} = ($me->{params}->{u} =~ m/^d/i) ? $RAD2DEG : 1.0;
  print "radial: conversion is $me->{params}->{angunit}\n" if($PDL::Transform::debug);

  $me->{name} = "radial (direct)";

  $me->{idim} = 2;
  $me->{odim} = 2;

  if($me->{params}->{r0}) {
    $me->{otype} = ["Azimuth", "Ln radius" . ($me->{params}->{r0} != 1.0 ? "/$me->{params}->{r0}" : "")];
    $me->{ounit} = [$me->{params}->{u},'']; # true-but-null prevents copying
  } else {
    $me->{otype} = ["Azimuth","Radius"];
    $me->{ounit} = [$me->{params}->{u},''];  # false value copies prev. unit
  }

  $me->{func} = sub {

      my($data,$o) = @_;

      my($out) = ($data->new_or_inplace);

      my($d) = $data->copy;
      my $tmp; # work around perl -d "feature"
      ($tmp = $d->slice("0:1")) -= $o->{origin};

      my($d0) = $d->slice("(0)");
      my($d1) = $d->slice("(1)");

      # (mod operator on atan2 puts everything in the interval [0,2*PI).)
      ($tmp = $out->slice("(0)")) .= (atan2(-$d1,$d0) % (2*$PI)) * $me->{params}->{angunit};

      ($tmp = $out->slice("(1)")) .= (defined $o->{r0}) ?
              0.5 * log( ($d1*$d1 + $d0 * $d0) / ($o->{r0} * $o->{r0}) ) :
              sqrt($d1*$d1 + $d0*$d0);

      $out;
  };

  $me->{inv} = sub {

    my($d,$o) = @_;
    my($d0,$d1,$out)=
        ( ($d->is_inplace) ?
          ($d->slice("(0)")->copy, $d->slice("(1)")->copy->dummy(0,2), $d) :
          ($d->slice("(0)"),       $d->slice("(1)")->dummy(0,2),       $d->copy)
          );

    $d0 /= $me->{params}->{angunit};

    my($os) = $out->slice("0:1");
    $os .= append(cos($d0)->dummy(0,1),-sin($d0)->dummy(0,1));
    $os *= defined $o->{r0}  ?  ($o->{r0} * exp($d1))  :  $d1;
    $os += $o->{origin};

    $out;
  };


  $me;
}

+======EOD_t_cylindrical======

pp_add_exported('t_quadratic');
pp_addpm(<<'+======EOD_t_quadratic======');

=head2 t_quadratic

=for usage

  $t = t_quadratic(<options>);

=for ref

Quadratic scaling -- cylindrical pincushion (n-d; with inverse)

Quadratic scaling emulates pincushion in a cylindrical optical system:
separate quadratic scaling is applied to each axis.  You can apply
separate distortion along any of the principal axes.  If you want
different axes, use L<t_wrap|/t_wrap> and L<t_linear|/t_linear> to rotate
them to the correct angle.  The scaling options may be scalars or
vectors; if they are scalars then the expansion is isotropic.

The formula for the expansion is:

    f(a) = ( <a> + <strength> * a^2/<L_0> ) / (abs(<strength>) + 1)

where <strength> is a scaling coefficient and <L_0> is a fundamental
length scale.   Negative values of <strength> result in a pincushion
contraction.

Note that, because quadratic scaling does not have a strict inverse for
coordinate systems that cross the origin, we cheat slightly and use
$x * abs($x)  rather than $x**2.  This does the Right thing for pincushion
and barrel distortion, but means that t_quadratic does not behave exactly
like t_cubic with a null cubic strength coefficient.

OPTIONS

=over 3

=item o,origin,Origin

The origin of the pincushion. (default is the, er, origin).

=item l,l0,length,Length,r0

The fundamental scale of the transformation -- the radius that remains
unchanged.  (default=1)

=item s,str,strength,Strength

The relative strength of the pincushion. (default = 0.1)

=item honest (default=0)

Sets whether this is a true quadratic coordinate transform.  The more
common form is pincushion or cylindrical distortion, which switches
branches of the square root at the origin (for symmetric expansion).
Setting honest to a non-false value forces true quadratic behavior,
which is not mirror-symmetric about the origin.

=item d, dim, dims, Dims

The number of dimensions to quadratically scale (default is the
dimensionality of your input vectors)


=back

=cut

sub t_quadratic {
    my($class) = 'PDL::Transform';
    my($o) = $_[0];
    if(ref $o ne 'HASH') {
        $o = {@_};
    }
    my($me) = PDL::Transform::new($class);

    $me->{params}->{origin} = _opt($o,['o','origin','Origin'],pdl(0));
    $me->{params}->{l0} = _opt($o,['r0','l','l0','length','Length'],pdl(1));
    $me->{params}->{str} = _opt($o,['s','str','strength','Strength'],pdl(0.1));
    $me->{params}->{dim} = _opt($o,['d','dim','dims','Dims']);
    $me->{name} = "quadratic";

    $me->{func} = sub {
        my($data,$o) = @_;
        my($dd) = $data->copy - $o->{origin};
        my($d) =  (defined $o->{dim}) ? $dd->slice("0:".($o->{dim}-1)) : $dd;
        $d += $o->{str} * ($d * abs($d)) / $o->{l0};
        $d /= (abs($o->{str}) + 1);
        $d += $o->{origin};
        if($data->is_inplace) {
            $data .= $dd;
            return $data;
        }
        $dd;
    };

    $me->{inv} = sub {
        my($data,$opt) = @_;
        my($dd) = $data->copy ;
        my($d) = (defined $opt->{dim}) ? $dd->slice("0:".($opt->{dim}-1)) : $dd;
        my($o) = $opt->{origin};
        my($s) = $opt->{str};
        my($l) = $opt->{l0};

        $d .= ((-1 + sqrt(1 + 4 * $s/$l * abs($d-$o) * (1+abs($s))))
            / 2 / $s * $l) * (1 - 2*($d < $o));
        $d += $o;
        if($data->is_inplace) {
            $data .= $dd;
            return $data;
        }
        $dd;
    };
    $me;
}

+======EOD_t_quadratic======

pp_add_exported('t_cubic');
pp_addpm(<<'+======EOD_t_cubic=======');

=head2 t_cubic

=for usage

  $t = t_cubic(<options>);

=for ref

Cubic scaling - cubic pincushion (n-d; with inverse)

Cubic scaling is a generalization of t_quadratic to a purely
cubic expansion.

The formula for the expansion is:

    f(a) = ( a' + st * a'^3/L_0^2 ) / (1 + abs(st)) + origin

where a'=(a-origin).  That is a simple pincushion
expansion/contraction that is fixed at a distance of L_0 from the
origin.

Because there is no quadratic term the result is always invertible with
one real root, and there is no mucking about with complex numbers or
multivalued solutions.


OPTIONS

=over 3

=item o,origin,Origin

The origin of the pincushion. (default is the, er, origin).

=item l,l0,length,Length,r0

The fundamental scale of the transformation -- the radius that remains
unchanged.  (default=1)


=item d, dim, dims, Dims

The number of dimensions to treat (default is the
dimensionality of your input vectors)

=back

=cut

sub t_cubic {
    my ($class) = 'PDL::Transform';
    my($o) = $_[0];
    if(ref $o ne 'HASH') {
        $o = {@_};
    }
    my($me) = PDL::Transform::new($class);

    $me->{params}->{dim} = _opt($o,['d','dim','dims','Dims'],undef);
    $me->{params}->{origin} = _opt($o,['o','origin','Origin'],pdl(0));
    $me->{params}->{l0} = _opt($o,['r0','l','l0','length','Length'],pdl(1));
    $me->{params}->{st} = _opt($o,['s','st','str'],pdl(0));
    $me->{name} = "cubic";

    $me->{params}->{cuberoot} = sub {
        my $a = shift;
        my $as = 1 - 2*($a<0);
        return $as * (  abs($a) ** (1/3) );
    };

    $me->{func} = sub {
        my($data,$o) = @_;
        my($dd) = $data->copy;
        my($d) = (defined $o->{dim}) ? $dd->slice("0:".($o->{dim}-1)) : $dd;

        $d -= $o->{origin};

        my $dl0 = $d / $o->{l0};

        # f(x) = x + x**3 * ($o->{st} / $o->{l0}**2):
        #     A = ($o->{st}/$dl0**2)
        #     B = 0
        #     C = 1
        #     D = -f(x)
        $d += $o->{st} * $d * $dl0 * $dl0;
        $d /= ($o->{st}**2 + 1);

        $d += $o->{origin};

        if($data->is_inplace) {
            $data .= $dd;
            return $data;
        }
        return $dd;
    };

    $me->{inv} = sub {
        my($data,$o) = @_;
        my($l) = $o->{l0};

        my($dd) = $data->copy;
        my($d) = (defined $o->{dim}) ? $dd->slice("0:".($o->{dim}-1)) : $dd;

        $d -= $o->{origin};
        $d *= ($o->{st}+1);

        # Now we have to solve:
        #  A x^3 + B X^2 + C x + D dd = 0
        # with the assignments above for A,B,C,D.
        # Since B is zero, this is greatly simplified - the discriminant is always negative,
        # so there is always exactly one real root.
        #
        # The only real hassle is creating a symmetric cube root; for convenience
        # is stashed in the params hash.

        # First: create coefficients for mnemonics.
        my ($A, $C, $D) = ( $o->{st} / $l / $l, 1, - $d );
        my $alpha =  27 * $A * $A * $D;
        my $beta =  3 * $A * $C;

        my $inner_root = sqrt( $alpha * $alpha   +   4 * $beta * $beta * $beta );

        $d .= (-1 / (3 * $A)) *
            (
              + &{$o->{cuberoot}}( 0.5 * ( $alpha + $inner_root ) )
              + &{$o->{cuberoot}}( 0.5 * ( $alpha - $inner_root ) )
            );

        $d += $origin;

        if($data->is_inplace) {
            $data .= $dd;
            return $data;
        } else {
            return $dd;
        }
    };

    $me;
}

+======EOD_t_cubic=======


pp_add_exported('t_quadratic');
pp_addpm(<<'======EOD_t_quadratic======');

=head2 t_quartic

=for usage

  $t = t_quartic(<options>);

=for ref

Quartic scaling -- cylindrical pincushion (n-d; with inverse)

Quartic scaling is a generalization of t_quadratic to a quartic
expansion.  Only even powers of the input coordinates are retained,
and (as with t_quadratic) sign is preserved, making it an odd function
although a true quartic transformation would be an even function.

You can apply separate distortion along any of the principal axes.  If
you want different axes, use L<t_wrap|/t_wrap> and
L<t_linear|/t_linear> to rotate them to the correct angle.  The
scaling options may be scalars or vectors; if they are scalars then
the expansion is isotropic.

The formula for the expansion is:

    f(a) = ( <a> + <strength> * a^2/<L_0> ) / (abs(<strength>) + 1)

where <strength> is a scaling coefficient and <L_0> is a fundamental
length scale.   Negative values of <strength> result in a pincushion
contraction.

Note that, because quadratic scaling does not have a strict inverse for
coordinate systems that cross the origin, we cheat slightly and use
$x * abs($x)  rather than $x**2.  This does the Right thing for pincushion
and barrel distortion, but means that t_quadratic does not behave exactly
like t_cubic with a null cubic strength coefficient.

OPTIONS

=over 3

=item o,origin,Origin

The origin of the pincushion. (default is the, er, origin).

=item l,l0,length,Length,r0

The fundamental scale of the transformation -- the radius that remains
unchanged.  (default=1)

=item s,str,strength,Strength

The relative strength of the pincushion. (default = 0.1)

=item honest (default=0)

Sets whether this is a true quadratic coordinate transform.  The more
common form is pincushion or cylindrical distortion, which switches
branches of the square root at the origin (for symmetric expansion).
Setting honest to a non-false value forces true quadratic behavior,
which is not mirror-symmetric about the origin.

=item d, dim, dims, Dims

The number of dimensions to quadratically scale (default is the
dimensionality of your input vectors)


=back

=cut

sub t_quartic {
    my($class) = 'PDL::Transform';
    my($o) = $_[0];
    if(ref $o ne 'HASH') {
        $o = {@_};
    }
    my($me) = PDL::Transform::new($class);

    $me->{params}->{origin} = _opt($o,['o','origin','Origin'],pdl(0));
    $me->{params}->{l0} = _opt($o,['r0','l','l0','length','Length'],pdl(1));
    $me->{params}->{str} = _opt($o,['s','str','strength','Strength'],pdl(0.1));
    $me->{params}->{dim} = _opt($o,['d','dim','dims','Dims']);
    $me->{name} = "quadratic";

    $me->{func} = sub {
        my($data,$o) = @_;
        my($dd) = $data->copy - $o->{origin};
        my($d) =  (defined $o->{dim}) ? $dd->slice("0:".($o->{dim}-1)) : $dd;
        $d += $o->{str} * ($d * abs($d)) / $o->{l0};
        $d /= (abs($o->{str}) + 1);
        $d += $o->{origin};
        if($data->is_inplace) {
            $data .= $dd;
            return $data;
        }
        $dd;
    };

    $me->{inv} = sub {
        my($data,$opt) = @_;
        my($dd) = $data->copy ;
        my($d) = (defined $opt->{dim}) ? $dd->slice("0:".($opt->{dim}-1)) : $dd;
        my($o) = $opt->{origin};
        my($s) = $opt->{str};
        my($l) = $opt->{l0};

        $d .= ((-1 + sqrt(1 + 4 * $s/$l * abs($d-$o) * (1+abs($s))))
            / 2 / $s * $l) * (1 - 2*($d < $o));
        $d += $o;
        if($data->is_inplace) {
            $data .= $dd;
            return $data;
        }
        $dd;
    };
    $me;
}

======EOD_t_quadratic======

pp_add_exported('t_spherical');
pp_addpm(<<'+======EOD_t_spherical======');

=head2 t_spherical

=for usage

    $t = t_spherical(<options>);

=for ref

Convert Cartesian to spherical coordinates.  (3-D; with inverse)

Convert 3-D Cartesian to spherical (theta, phi, r) coordinates.  Theta
is longitude, centered on 0, and phi is latitude, also centered on 0.
Unless you specify Euler angles, the pole points in the +Z direction
and the prime meridian is in the +X direction.  The default is for
theta and phi to be in radians; you can select degrees if you want
them.

Just as the L<t_radial|/t_radial> 2-D transform acts like a 3-D
cylindrical transform by ignoring third and higher dimensions,
Spherical acts like a hypercylindrical transform in four (or higher)
dimensions.  Also as with L<t_radial|/t_radial>, you must manually specify
the origin if you want to use more dimensions than 3.

To deal with latitude & longitude on the surface of a sphere (rather
than full 3-D coordinates), see
L<t_unit_sphere|PDL::Transform::Cartography/t_unit_sphere>.

OPTIONS:

=over 3

=item o, origin, Origin [default (0,0,0)]

This is the Cartesian origin of the spherical expansion.  Pass in a PDL
or an array ref.

=item e, euler, Euler [default (0,0,0)]

This is a 3-vector containing Euler angles to change the angle of the
pole and ordinate.  The first two numbers are the (theta, phi) angles
of the pole in a (+Z,+X) spherical expansion, and the last is the
angle that the new prime meridian makes with the meridian of a simply
tilted sphere.  This is implemented by composing the output transform
with a PDL::Transform::Linear object.

=item u, unit, Unit (default radians)

This option sets the angular unit to be used.  Acceptable values are
"degrees","radians", or reasonable substrings thereof (e.g. "deg", and
"rad", but "d" and "r" are deprecated).  Once genuine unit processing
comes online (a la Math::Units) any angular unit should be OK.

=back

=cut

sub t_spherical {
    my($class) = 'PDL::Transform';
    my($o) = $_[0];
    if(ref $o ne 'HASH') {
        $o = { @_ } ;
    }

    my($me) = PDL::Transform::new($class);

    $me->{idim}=3;
    $me->{odim}=3;

    $me->{params}->{origin} = _opt($o,['o','origin','Origin']);
    $me->{params}->{origin} = PDL->zeroes(3)
        unless defined($me->{params}->{origin});
    $me->{params}->{origin} = PDL->pdl($me->{params}->{origin});

    $me->{params}->{deg} = _opt($o,['d','degrees','Degrees']);

    my $unit = _opt($o,['u','unit','Unit']);
    $me->{params}->{angunit} = ($unit =~ m/^d/i) ?
        $DEG2RAD : undef;

    $me->{name} = "spherical";

    $me->{func} = sub {
        my($data,$o) = @_;
        my($d) = $data->copy - $o->{origin};

        my($d0,$d1,$d2) = ($d->slice("(0)"),$d->slice("(1)"),$d->slice("(2)"));
        my($out) =   ($d->is_inplace) ? $data : $data->copy;

        my $tmp; # work around perl -d "feature"
        ($tmp = $out->slice("(0)")) .= atan2($d1, $d0);
        ($tmp = $out->slice("(2)")) .= sqrt($d0*$d0 + $d1*$d1 + $d2*$d2);
        ($tmp = $out->slice("(1)")) .= asin($d2 / $out->slice("(2)"));

        ($tmp = $out->slice("0:1")) /= $o->{angunit}
          if(defined $o->{angunit});

        $out;
      };

    $me->{inv} = sub {
        my($d,$o) = @_;

        my($theta,$phi,$r,$out) =
    ( ($d->is_inplace) ?
              ($d->slice("(0)")->copy, $d->slice("(1)")->copy, $d->slice("(2)")->copy, $d) :
              ($d->slice("(0)"),       $d->slice("(1)"),       $d->slice("(2)"),       $d->copy)
              );


        my($x,$y,$z) =
            ($out->slice("(0)"),$out->slice("(1)"),$out->slice("(2)"));

        my($ph,$th);
        if(defined $o->{angunit}){
          $ph = $o->{angunit} * $phi;
          $th = $o->{angunit} * $theta;
        } else {
          $ph = $phi;
          $th = $theta;
        }

        $z .= $r * sin($ph);
        $x .= $r * cos($ph);
        $y .= $x * sin($th);
        $x *= cos($th);
        $out += $o->{origin};

        $out;
      };

    $me;
  }

+======EOD_t_spherical======

pp_add_exported('t_projective');
pp_addpm(<<'+======EOD_t_projective======');

=head2 t_projective

=for usage

    $t = t_projective(<options>);

=for ref

Projective transformation

Projective transforms are simple quadratic, quasi-linear
transformations.  They are the simplest transformation that
can continuously warp an image plane so that four arbitrarily chosen
points exactly map to four other arbitrarily chosen points.  They
have the property that straight lines remain straight after transformation.

You can specify your projective transformation directly in homogeneous
coordinates, or (in 2 dimensions only) as a set of four unique points that
are mapped one to the other by the transformation.

Projective transforms are quasi-linear because they are most easily
described as a linear transformation in homogeneous coordinates
(e.g. (x',y',w) where w is a normalization factor: x = x'/w, etc.).
In those coordinates, an N-D projective transformation is represented
as simple multiplication of an N+1-vector by an N+1 x N+1 matrix,
whose lower-right corner value is 1.

If the bottom row of the matrix consists of all zeroes, then the
transformation reduces to a linear affine transformation (as in
L<t_linear|/t_linear>).

If the bottom row of the matrix contains nonzero elements, then the
transformed x,y,z,etc. coordinates are related to the original coordinates
by a quadratic polynomial, because the normalization factor 'w' allows
a second factor of x,y, and/or z to enter the equations.

OPTIONS:

=over 3

=item m, mat, matrix, Matrix

If specified, this is the homogeneous-coordinate matrix to use.  It must
be N+1 x N+1, for an N-dimensional transformation.

=item p, point, points, Points

If specified, this is the set of four points that should be mapped one to the other.
The homogeneous-coordinate matrix is calculated from them.  You should feed in a
2x2x4 PDL, where the 0 dimension runs over coordinate, the 1 dimension runs between input
and output, and the 2 dimension runs over point.  For example, specifying

  p=> pdl([ [[0,1],[0,1]], [[5,9],[5,8]], [[9,4],[9,3]], [[0,0],[0,0]] ])

maps the origin and the point (0,1) to themselves, the point (5,9) to (5,8), and
the point (9,4) to (9,3).

This is similar to the behavior of fitwarp2d with a quadratic polynomial.

=back

=cut

sub t_projective {
  my($class) = 'PDL::Transform';
  my($o) = $_[0];
  if(ref $o ne 'HASH') {
    $o = { @_ };
  }

  my($me) = PDL::Transform::new($class);

  $me->{name} = "projective";

  ### Set options...


  $me->{params}->{idim} = $me->{idim} = _opt($o,['d','dim','Dim']);

  my $matrix;
  if(defined ($matrix=_opt($o,['m','matrix','Matrix']))) {
    $matrix = pdl($matrix);
    die "t_projective: needs a square matrix"
      if($matrix->dims != 2 || $matrix->dim(0) != $matrix->dim(1));

    $me->{params}->{idim} = $matrix->dim(0)-1
      unless(defined($me->{params}->{idim}));

    $me->{idim} = $me->{params}->{idim};

    die "t_projective: matrix not compatible with given dimension (should be N+1xN+1)\n"
      unless($me->{params}->{idim}==$matrix->dim(0)-1);

    my $inv = $matrix->inv;
    print STDERR "t_projective: warning - received non-invertible matrix\n"
      unless(all($inv*0 == 0));

    $me->{params}->{matrix} = $matrix;
    $me->{params}->{matinv} = $inv;

  } elsif(defined ($p=pdl(_opt($o,['p','point','points','Point','Points'])))) {
    die "t_projective: points array should be 2(x,y) x 2(in,out) x 4(point)\n\t(only 2-D points spec is available just now, sorry)\n"
      unless($p->dims==3 && all(pdl($p->dims)==pdl(2,2,4)));

    # Solve the system of N equations to find the projective transform
    my ($p0,$p1,$p2,$p3) = ( $p->slice(":,(0),(0)"), $p->slice(":,(0),(1)"), $p->slice(":,(0),(2)"), $p->slice(":,(0),(3)") );
    my ($P0,$P1,$P2,$P3) = ( $p->slice(":,(1),(0)"), $p->slice(":,(1),(1)"), $p->slice(":,(1),(2)"), $p->slice(":,(1),(3)") );
#print "declaring PDL...\n"    ;
    my $M = pdl( [ [$p0->at(0), $p0->at(1), 1,        0,        0, 0,  -$P0->at(0)*$p0->at(0), -$P0->at(0)*$p0->at(1)],
                   [       0,        0, 0, $p0->at(0), $p0->at(1), 1,  -$P0->at(1)*$p0->at(0), -$P0->at(1)*$p0->at(1)],
                   [$p1->at(0), $p1->at(1), 1,        0,        0, 0,  -$P1->at(0)*$p1->at(0), -$P1->at(0)*$p1->at(1)],
                   [       0,        0, 0, $p1->at(0), $p1->at(1), 1,  -$P1->at(1)*$p1->at(0), -$P1->at(1)*$p1->at(1)],
                   [$p2->at(0), $p2->at(1), 1,        0,        0, 0,  -$P2->at(0)*$p2->at(0), -$P2->at(0)*$p2->at(1)],
                   [       0,        0, 0, $p2->at(0), $p2->at(1), 1,  -$P2->at(1)*$p2->at(0), -$P2->at(1)*$p2->at(1)],
                   [$p3->at(0), $p3->at(1), 1,        0,        0, 0,  -$P3->at(0)*$p3->at(0), -$P3->at(0)*$p3->at(1)],
                   [       0,        0, 0, $p3->at(0), $p3->at(1), 1,  -$P3->at(1)*$p3->at(0), -$P3->at(1)*$p3->at(1)]
                   ] );
#print "ok.  Finding inverse...\n";
    my $h = ($M->inv x $p->slice(":,(1),:")->flat->slice("*1"))->slice("(0)");
#    print "ok\n";
    my $matrix = ones(3,3);
    my $tmp; # work around perl -d "feature"
    ($tmp = $matrix->flat->slice("0:7")) .= $h;
    $me->{params}->{matrix} = $matrix;

    $me->{params}->{matinv} = $matrix->inv;
  }


  $me->{params}->{idim} = 2 unless defined $me->{params}->{idim};
  $me->{params}->{odim} = $me->{params}->{idim};
  $me->{idim} = $me->{params}->{idim};
  $me->{odim} = $me->{params}->{odim};

  $me->{func} = sub {
    my($data,$o) = @_;
    my($id) = $data->dim(0);
    my($d) = $data->glue(0,ones($data->slice("0")));
    my($out) = ($o->{matrix} x $d->slice("*1"))->slice("(0)");
    return ($out->slice("0:".($id-1))/$out->slice("$id"));
  };

  $me->{inv} = sub {
    my($data,$o) = @_;
    my($id) = $data->dim(0);
    my($d) = $data->glue(0,ones($data->slice("0")));
    my($out) = ($o->{matinv} x $d->slice("*1"))->slice("(0)");
    return ($out->slice("0:".($id-1))/$out->slice("$id"));
  };

  $me;
}

+======EOD_t_projective======

pp_done();