Source

bllip-parser / second-stage / programs / features / spcfeatures.h

   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
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License.  You may obtain
// a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
// License for the specific language governing permissions and limitations
// under the License.

// spcfeatures.h
//
// Mark Johnson, forked from spefeatures.h on 14th November, 2005
//
// A spcfeature has extra-sentential context information
// 
#ifndef SPCFEATURES_H
#define SPCFEATURES_H

#include <algorithm>
#include <cassert>
#include <cstdio>
#include <ext/hash_map>
#include <iostream>
#include <limits>
#include <map>
#include <set>
#include <string>
#include <utility>
#include <vector>

#include "lexical_cast.h"
#include "sstring.h"
#include "sp-data.h"
#include "heads.h"
#include "popen.h"
#include "sptree.h"
#include "sym.h"
#include "tree.h"
#include "utility.h"

#define FloatTol 1e-7

// SPFEATURES_COMMON_DEFINITIONS contains all of the common definitions 
// that every feature function needs.
//
#define SPFEATURES_COMMON_DEFINITIONS					\
									\
  typedef ext::hash_map<Feature,Id> Feature_Id;				\
  Feature_Id feature_id;						\
									\
  virtual void extract_features(const sp_sentence_type& s) {		\
    extract_features_helper(*this, s);					\
  }									\
									\
  virtual Id prune_and_renumber(const size_type mincount, Id nextid,	\
				std::ostream& os) {			\
    return prune_and_renumber_helper(*this, mincount, nextid, os);	\
  }									\
									\
  virtual void feature_values(const sp_sentence_type& s,		\
			      Id_Floats& p_i_v)				\
  {									\
    feature_values_helper(*this, s, p_i_v);				\
  }                                                                     \
									\
  virtual std::ostream& print_feature_ids(std::ostream& os) const {	\
    return print_feature_ids_helper(*this, os);				\
  }									\
									\
  virtual std::istream& read_feature(std::istream& is, Id id) {		\
    return read_feature_helper(*this, is, id);				\
  }


extern int debug_level;
extern bool absolute_counts;    //!< produce absolute rather than relative counts
extern bool collect_correct;    //!< collect features from correct parse
extern bool collect_incorrect;  //!< collect features from incorrect parse
extern bool lowercase_flag;     //!< lowercase all terminals when reading tree

typedef unsigned int size_type;
typedef size_type Id;           //!< type of feature Ids
#define SCANF_ID_TYPE "%u"

typedef std::map<Id,Float> Id_Float;
typedef std::vector<Id_Float> Id_Floats;


////////////////////////////////////////////////////////////////////////
//                                                                    //
//                          FeatureClass{}                            //
//                                                                    //
////////////////////////////////////////////////////////////////////////

//! FeatureClass{} is an ABC for classes of features.  A FeatureClass
//! identifies features in parse trees.  To use the template functions
//! in FeatureClass and its descendants, each subclass of
//! FeatureClass{} should define the following embedded types as
//! well as the virtual functions of FeatureClass{}.
//!
//!   Feature    -- the type of features belonging to FeatureClass
//!                   (operator << should be defined on Feature)
//!
//!   Feature_Id -- an efficient map type from features to Id
//!
//! Each FeatureClass object must also have members:
//!
//! Feature_Id feature_id;
//
class FeatureClass {
public:
  
  typedef std::vector<int> Is;     //!< Is is a vector of int
  typedef std::vector<symbol> Ss;  //!< Ss is a vector of symbols

  //! destructor is virtual -- put it first so it isn't forgotten!
  //
  virtual ~FeatureClass() { };

  // These next virtual functions must be implemented by any FeatureClass
  
  //! identifier() returns a unique identifying string for this
  //! FeatureClass.  By convention, a FeatureClass::identifier() consists
  //! of a major class name followed by subclass specifications, all
  //! separated by ':'.  E.g., the identifier "RFrag:2:2:5" identifes the
  //! Rule Fragment feature class with 2 ancestors and fragment lengths
  //! between 2 and 5.
  //
  virtual const char* identifier() const = 0;

  //! extract_features() extracts the relevant features from sentence s
  //
  virtual void extract_features(const sp_sentence_type& s) = 0;

  //! prune_and_renumber() prunes all features with a count of
  //!  less than mincount and renumbers them from nextid.
  //!  It returns the updated nextid.  The pruned features are
  //!  written to os.
  //
  virtual Id prune_and_renumber(const size_type mincount, Id nextid, 
				std::ostream& os) = 0;

  //! feature_values() collects the feature values for the sentence s
  //
  virtual void feature_values(const sp_sentence_type& s, Id_Floats& piv) = 0;


  //! print_feature_ids() prints out the features and their ids.
  //
  virtual std::ostream& print_feature_ids(std::ostream& os) const = 0;


  //! read_feature() reads the feature definition from in, and
  //!  sets its id to id.
  //
  virtual std::istream& read_feature(std::istream& is, Id id) = 0;


  //! define commonly used symbols
  //
  inline static symbol endmarker() { static symbol e("_"); return e; }
  inline static symbol childmarker() { static symbol c("*CHILD*"); return c; }
  inline static symbol adjunctmarker() { static symbol a("*ADJ*"); return a; }
  inline static symbol conjunctmarker() { static symbol c("*CONJ*"); return c; }
  inline static symbol headmarker() { static symbol h("*HEAD*"); return h; }
  inline static symbol lastadjunctmarker() { static symbol l("*LASTADJ*"); return l; }
  inline static symbol lastconjunctmarker() { static symbol l("*LASTCONJ*"); return l; }
  inline static symbol rootmarker() { static symbol r("*ROOT*"); return r; }
  inline static symbol postheadmarker() { static symbol p("*POSTHEAD*"); return p; }
  inline static symbol preheadmarker() { static symbol p("*PREHEAD*"); return p; }

  inline static symbol DT() { static symbol dt("DT"); return dt; }
  inline static symbol NP() { static symbol np("NP"); return np; }
  inline static symbol ROOT() { static symbol root("ROOT"); return root; }
  inline static symbol S() { static symbol s("S"); return s; }
  inline static symbol SBAR() { static symbol sbar("SBAR"); return sbar; }
  inline static symbol SINV() { static symbol sinv("SINV"); return sinv; }
  inline static symbol VB() { static symbol vb("VB"); return vb; }
  inline static symbol VP() { static symbol vp("VP"); return vp; }

  //! quantize() is a utility function mapping positive ints to a
  //! small number of discrete values
  //
  inline static int quantize(int v) {
    assert(v >= 0);
    switch (v) {
    case 0: return 0;
    case 1: return 1;
    case 2: return 2;
    case 3:
    case 4: return 4;
    default: return 5;
    }
    return 5;
  }  // FeatureClass::quantize()

  //! symbol_quantize() is a utility function mapping positive ints to a
  //! small number of discrete values
  //
  inline symbol symbol_quantize(int v) {
    static symbol zero("0"), one("1"), two("2"), four("4"), five("5");
    assert(v >= 0);
    switch (v) {
    case 0: return zero;
    case 1: return one;
    case 2: return two;
    case 3:
    case 4: return four;
    default: return five;
    }
    return five;
  }  // FeatureClass::symbol_quantize()

  //! is_bounding_node() is true of nodes labeled ROOT, S or SBAR
  //
  inline static bool is_bounding_node(const sptree* node) {
    return node != NULL 
      && ( node->label.cat == ROOT()
	   || node->label.cat == S() || node->label.cat == SBAR() );
  }  // FeatureClass::is_bounding_node()


  //! in_root_clause() is true of nodes that are in the matrix or root clause.
  //
  inline static bool in_root_clause(const sptree* node) {
    while (!is_bounding_node(node) && node->label.parent) // up to bounding node
      node = node->label.parent;
    while (is_bounding_node(node) && node->label.parent) // over bounding nodes
      node = node->label.parent;
    if (node->label.parent == NULL)
      return true;
    else
      return false;
  }  // FeatureClass::in_root_clause()


  // The following templated static functions do most of the actual work;
  // the specialized FeatureClasses define a few data structures, and
  // the specialized virtual functions call the templated functions below.

  //! A FeatureParseVal object defines operator[] to accumulate feature counts
  //! for the parse with id parse
  //
  template <typename FeatClass>
  struct FeatureParseVal {
    typedef typename FeatClass::Feature F;
    typedef Float V;
    typedef std::map<size_type,V> C_V;
    typedef std::map<F,C_V> F_C_V;

    size_type parse;   // parse which we are currently collecting stats from
    F_C_V  f_p_v;   // feature -> parse -> value

    V& operator[](const F& feat) { return f_p_v[feat][parse]; }
  };  // FeatureClass::FeatureParseVal{}

  //! An IdParseVal object is like a FeatureParseVal object except that
  //! it maps each feature to its Id first
  //
  template <typename FeatClass>
  struct IdParseVal {
    typedef typename FeatClass::Feature Feature;
    typedef Id F;
    typedef Float V;
    typedef std::map<size_type,V> C_V;
    typedef std::map<F,C_V> F_C_V;

    FeatClass& fc;
    size_type  parse;
    F_C_V      f_p_v;
    V	       ignored;

    IdParseVal(FeatClass& fc) : fc(fc), ignored(0) { }

    V& operator[](const Feature& f) {
      typedef typename FeatClass::Feature_Id::const_iterator It;
      It it = fc.feature_id.find(f);
      if (it != fc.feature_id.end())
	return f_p_v[it->second][parse];
      else 
	return ignored;
    }  // IdParseVal::operator[]

  };  // FeatureClass::IdParseVal{}
      
  //! sentence_parsefidvals() calls parse_featurecount() to get the
  //!  feature count for each parse, then subtracts the most common
  //!  count for each feature from each count.  This means that feature
  //!  values can be negative!  Setting absolute_counts disables this.
  //
  template <typename FeatClass, typename Fid_Parse_Val, typename Parse_Fid_Val>
  static void sentence_parsefidvals(FeatClass& fc, const sp_sentence_type& s,
				    Fid_Parse_Val& fid_parse_val,
				    Parse_Fid_Val& parse_fid_val) {

    assert(parse_fid_val.size() == s.nparses());

    fid_parse_val.f_p_v.clear();

    for (size_type i = 0; i < s.nparses(); ++i) {
      fid_parse_val.parse = i;
      fc.parse_featurecount(fc, s.parses[i], fid_parse_val);
    }

    // copy into parse_fid_val, removing pseudo-constant features

    typedef typename Fid_Parse_Val::F F;
    typedef typename Fid_Parse_Val::V V;
    typedef typename Fid_Parse_Val::C_V C_V;
    typedef typename Fid_Parse_Val::F_C_V F_C_V;
    typedef std::map<V, size_type> V_C;

    cforeach (typename F_C_V, fit, fid_parse_val.f_p_v) {
      const F& feat = fit->first;
      const C_V& parse_val = fit->second;
      if (absolute_counts) {
	for (size_type i = 0; i < s.nparses(); ++i) {
	  V val = dfind(parse_val, i);
	  if (val != 0)
	    parse_fid_val[i][feat] = val;
	}
      }
      else {  // relative counts
	V_C val_gain;  // number of times each feature value occured
	for (size_type i = 0; i < s.nparses(); ++i) {
	  const V val = dfind(parse_val, i);
	  val_gain[val] += 2;
	  val_gain[val-1] += 1;
	}
	const V& highest_gain_val = max_element(val_gain, second_lessthan())->first;
	for (size_type i = 0; i < s.nparses(); ++i) {
	  const V val = dfind(parse_val, i) - highest_gain_val;
	  if (val != 0)
	    parse_fid_val[i][feat] = val;
	}
      }
    }
  }  // FeatureClass::sentence_parsefidvals()


  //! extract_features_helper() increments by one all of the non-pseudo-constant
  //! features that occur in one or more parses of this sentence.
  //
  template <typename FeatClass>
  static void extract_features_helper(FeatClass& fc, const sp_sentence_type& s) {

    if (s.nparses() <= 1)   // ignore unambiguous sentences
      return;

    typedef FeatureParseVal<FeatClass> FPV;
    typedef typename FPV::F_C_V F_C_V;
    typedef typename FPV::C_V C_V;
    typedef typename FPV::V V;

    FPV fpv;

    for (size_type i = 0; i < s.nparses(); ++i) {
      fpv.parse = i;
      fc.parse_featurecount(fc, s.parses[i], fpv);
    }

    // trace if required
    
    if (debug_level > 1000) {
      cforeach (typename F_C_V, it, fpv.f_p_v) {
	const C_V& p_v = it->second;
	typename C_V::const_iterator it1 = p_v.find(0);
	if (it1 != p_v.end())
	  std::cerr << '\t' << fc.identifier() 
		    << '\t' << it->first 
		    << '\t' << it1->second << std::endl;
      }
    }

    // only insert non-pseudo-constant features

    cforeach (typename F_C_V, it, fpv.f_p_v) {
      const C_V& p_v = it->second;
      bool pseudoconstant = true;
      if (p_v.size() != s.nparses()) // does feature occur on
	pseudoconstant = false;      //  every parse?
      else {
	assert(!p_v.empty());
	V v0 = p_v.begin()->second;
	cforeach (typename C_V, it1, p_v) 
	  if (it1->second != v0) {
	    pseudoconstant = false;
	    break;
	  }
      }
      if (pseudoconstant == false)
	if ((collect_correct && p_v.find(0) != p_v.end())
	    || (collect_incorrect 
		&& (p_v.find(0) == p_v.end() || p_v.size() > 1)))
	++fc.feature_id[it->first];
    }
  }  // FeatureClass::extract_features_helper()


  //! print_feature_ids_helper() prints the feature_ids
  //
  template <typename FeatClass>
  static std::ostream& print_feature_ids_helper(const FeatClass& fc, std::ostream& os) {
    typedef const typename FeatClass::Feature* FeaturePtr;
    typedef std::pair<Id,FeaturePtr> IdFeaturePtr;
    typedef std::vector<IdFeaturePtr> IdFeaturePtrs;
    IdFeaturePtrs idfps;;
    idfps.reserve(fc.feature_id.size());
    cforeach (typename FeatClass::Feature_Id, it, fc.feature_id)
      idfps.push_back(IdFeaturePtr(it->second, &it->first));
    std::sort(idfps.begin(), idfps.end());
    cforeach (typename IdFeaturePtrs, it, idfps)
      os << it->first
	 << '\t' << fc.identifier() 
	 << ' ' << *it->second
	 << '\n';
    os << std::flush;    
    return os;
  }  // FeatureClass::print_feature_ids_helper()


  //! prune_and_renumber_helper() extracts all features with at
  //! least mincount count, and numbers the remaining features
  //! incrementally from nextid. 
  //
  template <typename FeatClass>
  static Id prune_and_renumber_helper(FeatClass& fc, const size_type mincount,
				      Id nextid, std::ostream& os)
  {
    typedef typename FeatClass::Feature F;
    typedef std::vector<F> Fs;
    Fs fs;

    cforeach (typename FeatClass::Feature_Id, it, fc.feature_id) 
      if (it->second >= mincount) 
	fs.push_back(it->first);

    fc.feature_id.clear();

    cforeach (typename Fs, it, fs) 
      fc.feature_id[*it] = nextid++;

    print_feature_ids_helper(fc, os);
    return nextid;
  }  // FeatureClass::prune_and_renumber_helper()

  
  //! feature_values_helper() maps a sentence to its parse_id_count vector
  //
  template <typename FeatClass>
  static void feature_values_helper(FeatClass& fc, const sp_sentence_type& s, 
				    Id_Floats& p_i_v) 
  {
    assert(p_i_v.size() == s.nparses());

    IdParseVal<FeatClass> i_p_v(fc);
    sentence_parsefidvals(fc, s, i_p_v, p_i_v);
  } // FeatureClass::feature_values_helper()


  //! read_feature_helper() reads the next feature from is, and
  //! sets its id to id.  This method reads the entire rest of the
  //! line and defines the feature accordingly.
  //
  template <typename FeatClass>
  static std::istream&
  read_feature_helper(FeatClass& fc, std::istream& is, Id id)
  {
    typedef typename FeatClass::Feature F;
    typedef typename FeatClass::Feature_Id::value_type FI;
    F f;
    is >> f;
    assert(is);
    bool inserted = fc.feature_id.insert(FI(f, id)).second;
    if (!inserted) {
      std::cerr << "## Error in spfeatures:read_feature_helper(): "
		<< "duplicate feature, id = " << id
		<< ", f = `" << f << "'" << std::endl;
      exit(EXIT_FAILURE);
    }
    return is;
  }  // FeatureClass::read_feature_helper()

};  // FeatureClass{}


////////////////////////////////////////////////////////////////////////
//                                                                    //
//                          context_type{}                            //
//                                                                    //
////////////////////////////////////////////////////////////////////////

//! context_type{} stores information from the previous sentences
//! that can be conditioned on by following sentences.
//
struct context_type {

  typedef std::vector<symbol> Ss;
  std::string labelstem;      //!< stem from sentence label
  int labelnumber;            //!< number from sentence label
  symbol stype;               //!< type of sentence
  symbol last_stype;          //!< type of preceding sentence

  void update(const sp_sentence_type& s) {

    static symbol INIT("*INIT*");
    static symbol NONE("*NONE*");
    static symbol DQUOTE("''");
    static symbol FULLSTOP(".");

    assert(s.nparses() > 0);
    std::string newlabelstem;
    int newlabelnumber = 0;
    std::string::size_type pos =  s.label.rfind('.');
    if (pos != std::string::npos) {
      newlabelstem.assign(s.label, 0, pos);
      newlabelnumber = lexical_cast<int>(s.label.substr(pos+1));
    }
    else if (s.label.size() > 0)
      newlabelnumber = lexical_cast<int>(s.label);
    if (newlabelstem == labelstem && newlabelnumber == labelnumber+1) 
      last_stype = stype;
    else
      last_stype = INIT;

    std::vector<const sptree*> preterms;
    s.parses[0].parse->preterminal_nodes(preterms);
    size_type npreterms = preterms.size();
    assert(npreterms > 0);
    if (preterms[npreterms-1]->label.cat == FULLSTOP)
      stype = preterms[npreterms-1]->child->label.cat;
    else if (npreterms > 1 && preterms[npreterms-1]->label.cat == DQUOTE
	     && preterms[npreterms-2]->label.cat == FULLSTOP)
      stype = preterms[npreterms-2]->child->label.cat;
    else 
      stype = NONE;

    labelstem = newlabelstem;
    labelnumber = newlabelnumber;
  } // context_type::update()

};  // context_type{}


//! sentence_context is a global variable holding information from
//! the preceding context.  Yes, I know it would be better coding style
//! not to use a global variable, and to thread this variable though
//! the functions that use it.  But ugh, what a nuisance!
//
context_type sentence_context;


////////////////////////////////////////////////////////////////////////
//                                                                    //
//                       FeatureClassPtrs{}                           //
//                                                                    //
////////////////////////////////////////////////////////////////////////

//! FeatureClassPtrs{} holds pointers to FeatureClass{} objects.
//! These objects are responsible for identifying features in trees
//! and mapping a set of parse trees for a sentence to a vector
//! of feature-counts.
//!
//! In general, one or more FeatureClass pointers will be pushed
//! onto the FeatureClassPtrs object, then extract_features()
//! is called to count how many sentences each feature occurs
//! in, then prune_and_renumber() is called to prune features
//! and assign them id numbers, and finally write_features()
//! is called to map parse trees to feature vectors.
//
class FeatureClassPtrs : public std::vector<FeatureClass*> {

private:
  struct extract_features_visitor {
    struct FeatureClassPtrs& fcps;

    extract_features_visitor(FeatureClassPtrs& fcps) : fcps(fcps) { }
    
    void operator() (const sp_sentence_type& sentence) {

      assert(sentence.nparses() > 0);

      if (debug_level > 1000)
	std::cerr << '\n' << sentence.parses[0].parse << '\n' << std::endl;

      sentence_context.update(sentence);

      foreach (FeatureClassPtrs, it, fcps)
	(*it)->extract_features(sentence);

    }  // FeatureClassPtrs::extract_features_visitor::operator()

  };  // FeatureClassPtrs::extract_features_visitor{}


public:

  //! The following load FeatureClassPtrs with various sets of features
  //
  inline FeatureClassPtrs();

  inline void features_conj();
  inline void features_connll();
  inline void features_dp_27Aug05();
  inline void features_dp_31Aug05();
  inline void features_050831();
  inline void features_050902();
  inline void features_050904();
  inline void features_context0();

  //! extract_features() extracts features from the tree file infile.
  //
  void extract_features(const char* parseincmd, const char* goldincmd) {
    extract_features_visitor efv(*this);
    sp_corpus_type::map_sentences_cmd(parseincmd, goldincmd, efv, lowercase_flag);
  }  // FeatureClassPtrs::extract_features()


  //! prune_and_renumber() prunes all features that occur in less than
  //! mincount sentences, and then assigns them a number starting at 1.
  //
  Id prune_and_renumber(size_type mincount=5, std::ostream& os=std::cout) {
    Id nextid = 0;
    cforeach (FeatureClassPtrs, it, *this)
      nextid = (*it)->prune_and_renumber(mincount, nextid, os);
    return nextid;
  }  // FeatureClassPtrs::prune_and_renumber()

  
  //! write_features() maps a tree data file into a feature
  //! data file.  This is used to prepare a feature counts
  //! file from a tree data file.
  //
  void write_features(const char* parseincmd, const char* goldincmd,
		      const char* outfile) {

    const char* filesuffix = strrchr(outfile, '.');
    std::string command(strcasecmp(filesuffix, ".bz2") 
			? (strcasecmp(filesuffix, ".gz") 
			   ? "cat > " : "gzip > ")
			: "bzip2 > ");
    command += outfile;
    FILE *out = popen(command.c_str(), "w");
    if (out == NULL) {
      std::cerr << "## Error: can't popen command " << command << std::endl;
      exit(EXIT_FAILURE);
    }
    command.clear();

    FILE* parsein = popen(parseincmd, "r");

    if (parsein == NULL) {
      std::cerr << "## Error: can't popen parseincmd = " << parseincmd << std::endl;
      exit(EXIT_FAILURE);
    }

    FILE* goldin = popen(goldincmd, "r");

    if (!goldin) {
      std::cerr << "## Error: can't popen goldincmd = " << goldincmd << std::endl;
      exit(EXIT_FAILURE);
    }

    unsigned int nsentences;
    int nread = fscanf(goldin, " %u ", &nsentences);
    if (nread != 1) {
      std::cerr << "## Failed to read nsentences from " 
		<< goldincmd << std::endl;
      exit(EXIT_FAILURE);
    }
    fprintf(out, "S=%u\n", nsentences);

    sp_sentence_type sentence;
    Id_Floats p_i_v;
    for (size_type i = 0; i < nsentences; ++i) {
      if (!sentence.read(parsein, goldin, lowercase_flag)) {
	std::cerr << "## Error reading sentence " << i+1  
		  << " from \"" << parseincmd << "\" and \"" << goldincmd << "\""
		  << std::endl;
	exit(EXIT_FAILURE);
      }

      assert(sentence.nparses() > 0);

      sentence_context.update(sentence);

      precrec_type::edges goldedges(sentence.gold);
      fprintf(out, "G=%u N=%u", goldedges.nedges(), unsigned(sentence.parses.size()));
      p_i_v.clear();                     // Clear feature-counts
      p_i_v.resize(sentence.nparses());
      cforeach (FeatureClassPtrs, it, *this)
	(*it)->feature_values(sentence, p_i_v);

      for (size_type j = 0; j < sentence.parses.size(); ++j) {
	const sp_parse_type& p = sentence.parses[j];
	precrec_type pr(goldedges, p.parse);
	fprintf(out, " P=%u W=%u", pr.ntest, pr.ncommon);
	const Id_Float& i_v = p_i_v[j];
	cforeach (Id_Float, it, i_v) 
	  if (it->second == 1)
	    fprintf(out, " " SCANF_ID_TYPE, it->first);
	  else 
	    fprintf(out, " " SCANF_ID_TYPE "=%g", it->first, it->second);
	fprintf(out, ",");
      }
      fprintf(out, "\n");
    }

    pclose(goldin);
    pclose(parsein);
    pclose(out);
  }  // FeatureClassPtrs::write_features()

  //! read_feature_ids() reads feature ids from is, and sets
  //! each feature class' feature_id hash accordingly.
  //
  Id read_feature_ids(std::istream& is) {
    typedef std::map<std::string, FeatureClass*> St_FCp;
    St_FCp fcident_fcp;
    for (iterator it = begin(); it != end(); ++it) 
      fcident_fcp[(*it)->identifier()] = *it;

    Id id, maxid = 0;
    std::string fcident;
    while (is >> id >> fcident) {
      St_FCp::const_iterator it = fcident_fcp.find(fcident);
      if (it != fcident_fcp.end()) 
	it->second->read_feature(is, id);
      else {
	std::cerr << "## Error: can't find feature identifier " << fcident
		  << " in feature list.\n"
		  << "## best-parses incompatible with feature definition data file."
		  << std::endl;
	exit(EXIT_FAILURE);
      }
      
      is.ignore(std::numeric_limits<int>::max(), '\n');
      if (id > maxid)
	maxid = id;
    }
    return maxid;
  }  // FeatureClassPtrs::read_feature_ids()

  //! best_parse() returns the best parse tree from n-best parses for a sentence
  //
  template <typename Ws>
  const tree* best_parse(const sp_sentence_type& sentence, const Ws& ws) const {
    assert(sentence.nparses() > 0);

    sentence_context.update(sentence);

    Id_Floats p_i_v(sentence.nparses());
    cforeach (FeatureClassPtrs, it, *this)
      (*it)->feature_values(sentence, p_i_v);

    Float max_weight = 0;
    size_type i_max = 0;
    for (size_type i = 0; i < sentence.nparses(); ++i) {
      const Id_Float& i_v = p_i_v[i];
      Float w = 0;
      cforeach (Id_Float, ivit, i_v) {
	assert(ivit->first < ws.size());
	w += ivit->second * ws[ivit->first];
      }
      if (i == 0 || w > max_weight) {
	i_max = i;
	max_weight = w;
      }
    }
    return sentence.parses[i_max].parse0;
  } // FeatureClassPtrs::best_parse()


  //! write_ranked_trees() sorts all of the trees by their conditional
  //! probability and then writes them out in sorted order.
  //
  template <typename Ws>
  std::ostream& write_ranked_trees(const sp_sentence_type& sentence, 
				   const Ws& ws, std::ostream& os) const {
    assert(sentence.nparses() > 0);

    sentence_context.update(sentence);

    os << sentence.nparses() << ' ' << sentence.label << std::endl;

    Id_Floats p_i_v(sentence.nparses());
    cforeach (FeatureClassPtrs, it, *this)
      (*it)->feature_values(sentence, p_i_v);

    typedef std::pair<Id,Float> IdFloat;
    typedef std::vector<IdFloat> IdFloats;

    IdFloats idweights(sentence.nparses());

    for (size_type i = 0; i < sentence.nparses(); ++i) {
      idweights[i].first = i;
      const Id_Float& i_v = p_i_v[i];
      Float w = 0;
      cforeach (Id_Float, ivit, i_v) {
	assert(ivit->first < ws.size());
	w += ivit->second * ws[ivit->first];
      }
      idweights[i].second = w;
    }

    std::sort(idweights.begin(), idweights.end(), second_greaterthan());
    
    cforeach (IdFloats, it, idweights) {
      const sp_parse_type& parse = sentence.parses[it->first];
      os << it->second << ' ' << parse.logprob << '\n';
      write_tree_noquote_root(os, parse.parse0);
      os << std::endl;
    }
    return os;
  } // FeatureClassPtrs::write_ranked_trees()

  //! write_features_debug() writes out the features associated with each parse.
  //
  template <typename Ws>
  std::ostream& write_features_debug(const sp_sentence_type& sentence,
				     const Ws& ws, std::ostream& os) const {
    assert(sentence.nparses() > 0);

    sentence_context.update(sentence);

    Id_Floats p_i_v(sentence.nparses());
    cforeach (FeatureClassPtrs, it, *this)
      (*it)->feature_values(sentence, p_i_v);

    for (size_type i = 0; i < sentence.nparses(); ++i) {
      const Id_Float& i_v = p_i_v[i];
      cforeach (Id_Float, ivit, i_v) {
	if (ivit->first == 0) continue;      // skip first feature
	if (ws[ivit->first] == 0) continue;  // skip features with zero weight
	os << sentence.label << ' ' 
	   << i << ' '
	   << ivit->first << ' '
	   << ivit->second << std::endl;
      }
    }
    return os;
  } // FeatureClassPtrs::write_features_debug()
};  // FeatureClassPtrs{}


std::ostream& operator<< (std::ostream& os, const FeatureClassPtrs& fcps) {
  cforeach (FeatureClassPtrs, it, fcps)
    (*it)->print_feature_ids(os);
  return os;
}  // operator<<(FeatureClassPtrs&)

////////////////////////////////////////////////////////////////////////
//                                                                    //
//                     FeatureClass{} specializations                 //
//                                                                    //
////////////////////////////////////////////////////////////////////////


//! NLogP is the - log parse probability
//!
//! The identifier is NLogP
//
class NLogP : public FeatureClass {
public:

  typedef int Feature;  // Always zero

  std::string identifier_string;

  NLogP() : identifier_string("NLogP") { }

  template <typename FeatClass, typename Feat_Count>
  void parse_featurecount(FeatClass& fc, const sp_parse_type& parse,
			  Feat_Count& feat_count) {
    feat_count[0] -= parse.logprob;
  }  // NLogP::parse_featurecount();

  // Here is the stuff that every feature needs

  virtual const char *identifier() const {
    return identifier_string.c_str();
  }  // NLogP::identifier()

  // These virtual functions just pass control to the static template functions
  //
  SPFEATURES_COMMON_DEFINITIONS;
  
}; // NLogP{}


//! NLogCondP is the - log conditional probability of the parse
//!
//! The identifier is LogCondP
//
class NLogCondProb : public FeatureClass {
public:

  typedef int Feature;  // Always zero

  std::string identifier_string;

  NLogCondProb() : identifier_string("NLogCondP") { }

  template <typename FeatClass, typename Feat_Count>
  void parse_featurecount(FeatClass& fc, const sp_parse_type& parse,
			  Feat_Count& feat_count) {
    feat_count[0] -= parse.logcondprob;
  }  // LogCondP::parse_featurecount();

  // Here is the stuff that every feature needs

  virtual const char *identifier() const {
    return identifier_string.c_str();
  }  // NLogCondP::identifier()

  // These virtual functions just pass control to the static template functions
  //
  SPFEATURES_COMMON_DEFINITIONS;
  
}; // NLogCondP{}


//! BinnedLogCondP defines features which count binned log conditional 
//!  probabilities of a parse.
//!
//! The identifier is BinnedLogCondP:nbins:base, where nbins is the number of
//! probability bins and base is the base of the log used.
//
class BinnedLogCondP : public FeatureClass {
public:
  
  typedef int Feature;  // Feature is the bin number

  int nbins;
  Float base; 
  Float log_base;
  std::string identifier_string;

  BinnedLogCondP(int nbins=7, Float base=2) 
    : nbins(nbins), base(base), log_base(log(base)),
      identifier_string("BinnedLogCondP:") {
    (identifier_string += lexical_cast<std::string>(nbins)) += ':';
    identifier_string += lexical_cast<std::string>(base);
  } // BinnedLogCondP::BinnedLogCondP()

  template <typename FeatClass, typename Feat_Count>
  void parse_featurecount(FeatClass& fc, const sp_parse_type& parse,
			  Feat_Count& feat_count) {
    int bin = std::max(1, std::min(nbins, int(-parse.logcondprob/log_base)));
    ++feat_count[bin];
  }  // BinnedLogCondP::parse_featurecount();

  // Here is the stuff that every feature needs

  virtual const char *identifier() const {
    return identifier_string.c_str();
  }  // BinnedLogCondP::identifier()

  // These virtual functions just pass control to the static template functions
  //
  SPFEATURES_COMMON_DEFINITIONS;
  
}; // BinnedLogCondP{}


//! InterpLogCondP defines features which count binned log conditional probabilities
//! of a parse.
//!
//! The identifier is InterpLogCondP:nbins:base, where nbins is the number of
//! probability bins and base is the base of the log used.
//
class InterpLogCondP : public FeatureClass {
public:
  
  typedef int Feature;  // Feature is the bin number

  int nbins;
  Float base; 
  Float log_base;
  std::string identifier_string;

  InterpLogCondP(int nbins=7, Float base=2) 
    : nbins(nbins), base(base), log_base(log(base)),
      identifier_string("InterpLogCondP:") {
    (identifier_string += lexical_cast<std::string>(nbins)) += ':';
    identifier_string += lexical_cast<std::string>(base);
  } // InterpLogCondP::InterpLogCondP()

  template <typename FeatClass, typename Feat_Count>
  void parse_featurecount(FeatClass& fc, const sp_parse_type& parse,
			  Feat_Count& feat_count) {
    int bin = std::max(1, std::min(nbins, int(-parse.logcondprob/log_base)));
    feat_count[bin] += -parse.logcondprob/log_base;
  }  // InterpLogCondP::parse_featurecount();

  // Here is the stuff that every feature needs

  virtual const char *identifier() const {
    return identifier_string.c_str();
  }  // InterpLogCondP::identifier()

  // These virtual functions just pass control to the static template functions
  //
  SPFEATURES_COMMON_DEFINITIONS;
  
}; // InterpLogCondP{}


//! A TreeFeatureClass is an ABC for classes of features where the
//! feature count for a parse is defined by the parse's tree (most
//! features are like this).
//!
//! Every subclass to TreeFeatureClass must define a method:
//!
//!  tree_featurecount(fc, tp, feat_count);
//
class TreeFeatureClass : public FeatureClass {
public:

  //! parse_featurecount() passes the tree to tree_featurecount()
  //! to analyse.
  //
  template <typename FeatClass, typename Feat_Count>
  static void parse_featurecount(FeatClass& fc, const sp_parse_type& p,
				 Feat_Count& feat_count) {
    assert(p.parse != NULL);
    fc.tree_featurecount(fc, p.parse, feat_count);
  }  // TreeFeatureClass::parse_featurecount()

};  // TreeFeatureClass{}

//! A NodeFeatureClass is an ABC for classes of features where the
//! feature count for a tree is the sum of the feature counts for
//! each node.
//!
//! Every subclass to NodeFeatureClass must define a method:
//!
//!  node_featurecount(fc, tp, feat_count);
//
class NodeFeatureClass : public TreeFeatureClass {
public:
  
  //! tree_featurecount() sums the features on each node to get
  //!  the feature count on each tree
  //
  template <typename FeatClass, typename Feat_Count>
  static void tree_featurecount(FeatClass& fc, const sptree* tp, 
				Feat_Count& feat_count) {
    assert(tp != NULL);
    fc.node_featurecount(fc, tp, feat_count);
    if (tp->is_nonterminal())
      tree_featurecount(fc, tp->child, feat_count);
    if (tp->next != NULL)
      tree_featurecount(fc, tp->next, feat_count);
  }  // NodeFeatureClass::tree_featurecount()

};  // NodeFeatureClass{}

//! A RuleFeatureClass is an ABC for classes of features
//! with rule-like features
//!
class RuleFeatureClass : public NodeFeatureClass {
public:
  
  enum annotation_level { none, pos, lexical };
  enum annotation_type { semantic, syntactic };
  enum root_level { noroot, rootonly, roottype, lastroottype };

  RuleFeatureClass(std::string identifier_stem,   //!< Stem of identifier
		   size_type nanccats,            //!< Number of ancestor categories above trees
		   root_level label_root,	  //!< Annotate with "in root context"
		   bool label_conjunct,           //!< Annotate with "belongs to conjunction"
		   annotation_level head,         //!< Amount of head annotation 
		   annotation_level functional,   //!< Amount of function word annotation
		   annotation_level all,          //!< Amount of lexical word annotation
		   annotation_type type           //!< Head type
		   ) : nanccats(nanccats), label_root(label_root), label_conjunct(label_conjunct),
		       head(head), functional(functional), all(all), type(type),
		       identifier_string(identifier_stem), 
		       max_annotation_level(std::max(head,std::max(functional,all)))  
  {
    identifier_string += ":";
    identifier_string += lexical_cast<std::string>(nanccats) + ":";
    identifier_string += lexical_cast<std::string>(label_root) + ":";
    identifier_string += lexical_cast<std::string>(label_conjunct) + ":";
    identifier_string += lexical_cast<std::string>(head) + ":";
    identifier_string += lexical_cast<std::string>(functional) + ":";
    identifier_string += lexical_cast<std::string>(all) + ":";
    identifier_string += lexical_cast<std::string>(type);
  } // RuleFeatureClass::RuleFeatureClass()

  const size_type nanccats;
  const root_level label_root;
  const bool label_conjunct;
  const annotation_level head;         //!< annotation on rule's head
  const annotation_level functional;   //!< annotation on (projections of) functional categories
  const annotation_level all;          //!< annotation on all words
  const annotation_type type;          //!< syntactic or semantic annotation

  std::string identifier_string;
  const annotation_level max_annotation_level;

  typedef Ss Feature;
  
  //! push_child_features() pushes the features for this child node 
  //
  void push_child_features(const sptree* node, const sptree* parent, Feature& f,
			   annotation_level& highest_level) 
  {
    const sptree* parent_headchild
      = (type == semantic 
	 ? parent->label.semantic_headchild : parent->label.syntactic_headchild);
    bool is_headchild = (node == parent_headchild);

    const sptree_label& label = node->label;
    f.push_back(label.cat);
    const sptree* lexhead 
      = (type == semantic ? label.semantic_lexhead : label.syntactic_lexhead);
    if (lexhead == NULL)
      return;
    if (all < pos 
	&& (!lexhead->is_functional() || functional < pos)
	&& (!is_headchild || head < pos))
      return;
    if (lexhead != node) {
      f.push_back(headmarker());
      f.push_back(lexhead->label.cat);
      highest_level = std::max(highest_level, pos);
    }
    if (all < lexical 
	&& (!lexhead->is_functional() || functional < lexical)
	&& (!is_headchild || head < lexical))
      return;
    f.push_back(lexhead->child->label.cat);
    highest_level = std::max(highest_level, lexical);
  }  // RuleFeatureClass::push_child_features()

  //! push_ancestor_features() pushes features for ancestor nodes.
  //
  void push_ancestor_features(const sptree* node, Feature& f) {

    f.push_back(endmarker());
    
    const sptree* parent = node->label.parent;
    for (size_type i = 0; i <= nanccats && parent != NULL; ++i) {
      f.push_back(node->label.cat);
      if (label_conjunct && parent != NULL) {
	if (parent->is_coordination()) 
	  f.push_back(parent->is_last_nonpunctuation() 
		      ? lastconjunctmarker() : conjunctmarker());
	else if (parent->is_adjunction())
	  f.push_back(parent->is_last_nonpunctuation()
		      ? lastadjunctmarker() : adjunctmarker());
      }
      node = parent;
      parent = node->label.parent;
    }
    
    if (in_root_clause(node)) {
      if (label_root == rootonly)
	f.push_back(rootmarker());
      else if (label_root == roottype)
	f.push_back(sentence_context.stype);
    }

    if (label_root == lastroottype)
      f.push_back(sentence_context.last_stype);
  }  // RuleFeatureClass::push_top_ancestor_features()

  virtual const char *identifier() const {
    return identifier_string.c_str();
  }  // RuleFeatureClass::identifier()

};  // RuleFeatureClass{}

//! Identifier is Rule:<nanctrees>:<nanccats>:<root>:<conj>:<head>:<functional>:<all>:<type>
//!
class Rule : public RuleFeatureClass {
public:
  
  Rule(size_type nanctrees = 0,         //!< Number of ancestor local trees
       size_type nanccats = 0,          //!< Number of ancestor categories above trees
       root_level label_root = noroot,  //!< Annotate with "in root context"
       bool label_conjunct = false,     //!< Annotate with "belongs to conjunction"
       annotation_level head = none,    //!< Amount of head annotation 
       annotation_level functional = none, //!< Amount of function word annotation
       annotation_level all = none,     //!< Amount of lexical word annotation
       annotation_type type = syntactic
       ) : RuleFeatureClass(std::string("Rule:")+lexical_cast<std::string>(nanctrees), 
			    nanccats, label_root, label_conjunct, head, 
			    functional, all, type),
	   nanctrees(nanctrees) { } // Rule::Rule()

  size_type nanctrees;

  template <typename FeatClass, typename Feat_Count>
  void node_featurecount(FeatClass& fc, const sptree* node, 
			 Feat_Count& feat_count) {

    if (!node->is_nonterminal())
      return;

    Feature f;
    annotation_level highest_level = none;

    // push (possibly lexicalized) children
    
    for (const sptree* child = node->child; child != NULL; child = child->next) 
      push_child_features(child, node, f, highest_level);

    // push (possibly lexicalized) ancestor rules

    for (size_type i = 0; i < nanctrees && node->label.parent != NULL; ++i) {
      f.push_back(endmarker());
      for (const sptree* child = node->label.parent->child; child != NULL; 
	   child = child->next)
	if (child == node) {
	  f.push_back(childmarker());
	  f.push_back(child->label.cat);
	}
	else
	  push_child_features(child, node, f, highest_level);
      node = node->label.parent;
    }
    
    if (highest_level != max_annotation_level)
      return;

    push_ancestor_features(node, f);
    ++feat_count[f];
  }  // Rule::node_featurecount()

  // Here is the stuff that every feature needs

  SPFEATURES_COMMON_DEFINITIONS;
};  // Rule{}


//! NGram
//!
//! Identifier is NGram:<frag_len>:<nanccats>:<root>:<conj>:<head>:<functional>:<all>:<type>
//
class NGram : public RuleFeatureClass {
public:

  NGram(size_type fraglen = 3,           //!< Number of children in sequence
	size_type nanccats = 1,          //!< Number of ancestor categories above trees
	root_level label_root = noroot,	 //!< Annotate with "in root context"
	bool label_conjunct = false,     //!< Annotate with "belongs to conjunction"
	annotation_level head = none,    //!< Amount of head annotation 
	annotation_level functional = none, //!< Amount of function word annotation
	annotation_level all = none,     //!< Amount of lexical word annotation
	annotation_type type = syntactic
	) : RuleFeatureClass(std::string("NGram:")+lexical_cast<std::string>(fraglen), 
			     nanccats, label_root, label_conjunct, head, functional, 
			     all, type), 
	    fraglen(fraglen) { }

  size_type fraglen;

  template <typename FeatClass, typename Feat_Count>
  void node_featurecount(FeatClass& fc, const sptree* node, Feat_Count& feat_count) 
  {
    if (!node->is_nonterminal())
      return;

    size_type nchildren = 0;
    for (const sptree* child = node->child; child != NULL; child = child->next)
      ++nchildren;

    if (nchildren < fraglen)
      return;

    const sptree* headchild = (type == semantic 
			       ? node->label.semantic_headchild 
			       : node->label.syntactic_headchild);

    typedef std::vector<const sptree*> Tptrs;
    Tptrs children;

    children.push_back(NULL);
    for (const sptree* child = node->child; child != NULL; child = child->next) 
      children.push_back(child);
    children.push_back(NULL);

    symbol headposition = preheadmarker();

    for (size_type start = 0; start+fraglen <= children.size(); ++start) {
      if (children[start] == headchild)
	headposition = postheadmarker();

      Feature f;
      annotation_level highest_level = none;
      bool includes_headchild = false;

      for (size_type pos = start; pos < start+fraglen; ++pos) {
	const sptree* child = children[pos];
	if (child != NULL) 
	  push_child_features(child, node, f, highest_level);
	else
	  f.push_back(endmarker());
	if (child == headchild)
	  includes_headchild = true;
      }

      f.push_back(headposition);

      if (includes_headchild == false && head != none)
	push_child_features(headchild, node, f, highest_level);

      if (highest_level != max_annotation_level)
	return;
      
      push_ancestor_features(node, f);

      ++feat_count[f];
    }
  }  // NGram::node_featurecount()
 
  SPFEATURES_COMMON_DEFINITIONS;
};  // NGram{}
  

//! Word{} collects information on words in their vertical context.
//!
//! Identifier is Word:<nanccats>
//!
class Word : public NodeFeatureClass {
public:
  
  Word(size_type nanccats = 1)        //!< Number of ancestor local trees
    : nanccats(nanccats), identifier_string("Word:")
  {
    identifier_string += lexical_cast<std::string>(nanccats);
  } // Word::Word()

  const size_type nanccats;
  std::string identifier_string;

  typedef Ss Feature;
  
  template <typename FeatClass, typename Feat_Count>
  void node_featurecount(FeatClass& fc, const sptree* node, 
			 Feat_Count& feat_count) {

    if (!node->is_preterminal())
      return;
    
    Feature f;
    f.push_back(node->child->label.cat);

    for (size_type i = 0; i < nanccats; ++i) {
      if (node == NULL)
	return;
      f.push_back(node->label.cat);
      node = node->label.parent;
    }
    
    ++feat_count[f];
  }  // Word::node_featurecount()

  // Here is the stuff that every feature needs

  virtual const char *identifier() const {
    return identifier_string.c_str();
  }  // Word::identifier()

  SPFEATURES_COMMON_DEFINITIONS;
};  // Word{}


//! WProj{} collects information on words in their vertical context.
//! It projects each word up to its maximal projection.
//!
//! Identifier is WProj:<HeadType>:<IncludeNonMaximal>:<NAncs>
//!
class WProj : public NodeFeatureClass {
public:

  enum annotation_type { semantic, syntactic };
  
  WProj(annotation_type type = semantic,  //!< Head type
	bool include_nonmaximal = false,  //!< Only include maximal projection
	size_type nancs = 1)                 //!< Extra ancestors to include
    : type(type), include_nonmaximal(include_nonmaximal), nancs(nancs), 
      identifier_string("WProj:")
  {
    (identifier_string += lexical_cast<std::string>(type)) += ':';
    (identifier_string += lexical_cast<std::string>(include_nonmaximal)) += ':';
    identifier_string += lexical_cast<std::string>(nancs);
  } // WProj::WProj()

  annotation_type type;
  bool include_nonmaximal;
  size_type nancs;
  std::string identifier_string;

  typedef std::vector<symbol> Feature;
  
  template <typename FeatClass, typename Feat_Count>
  void node_featurecount(FeatClass& fc, const sptree* node, 
			 Feat_Count& feat_count) {

    if (node->is_punctuation() || !node->is_preterminal())
      return;
    
    Feature f;
    f.push_back(node->child->label.cat);

    while (node->label.parent) {
      const sptree* parent = node->label.parent;
      const sptree* parent_headchild
	= (type == semantic 
	   ? parent->label.semantic_headchild : parent->label.syntactic_headchild);
      bool is_headchild = (node == parent_headchild && !parent->is_root());
      if (is_headchild) {
	if (include_nonmaximal)
	  f.push_back(node->label.cat);
      }
      else
	break;
      node = parent;
    }
    
    for (size_type i = 0; node != NULL && i <= nancs; node = node->label.parent, ++i) 
      f.push_back(node->label.cat);
      
    ++feat_count[f];
  }  // WProj::node_featurecount()

  // Here is the stuff that every feature needs

  virtual const char *identifier() const {
    return identifier_string.c_str();
  }  // WProj::identifier()


  SPFEATURES_COMMON_DEFINITIONS;
};  // WProj{}


//! The RightBranch defines two features: 1, which is true
//! of lexical nodes on the right-most branch and 0, which is true of
//! nodes that are not on the right-most branch.
//
class RightBranch : public TreeFeatureClass {
public:

  //! tree_featurecount() counts the number of nodes on a right branch
  //
  template <typename FeatClass, typename Feat_Count>
  static void tree_featurecount(FeatClass& fc, const sptree* tp, 
				Feat_Count& feat_count) {
    rightbranch_count(tp, 1, feat_count);
  }  // RightBranch::tree_featurecount()

  //! rightbranch_count() is called with rightmost==1 iff the parent was
  //! on the rightmost branch.
  //
  template <typename Feat_Count>
  static int rightbranch_count(const sptree* tp, int rightmost, Feat_Count& fc) {
    if (tp->next) 
      rightmost = rightbranch_count(tp->next, rightmost, fc);
    if (tp->is_punctuation())
      return rightmost;
    ++fc[rightmost];
    if (tp->is_nonterminal())
      rightbranch_count(tp->child, rightmost, fc);
    return 0;
  }  // RightBranch::rightbranch_count()

  // required types

  typedef int Feature;    // 0 = non-rightmost branch, 1 = rightmost branch

  virtual const char* identifier() const {
    static char p[] = "RightBranch";
    return p;
  }  // RightBranch::identifier()

  SPFEATURES_COMMON_DEFINITIONS;
}; // RightBranch{}


//! LeftBranchLength is a feature whose value is the log of 
//! the length of the left-branching chain terminating in
//! each preterminal.
//!
//! Identifier is LeftBranchLength
//
class LeftBranchLength : public TreeFeatureClass {
public:

  //! tree_featurecound() counts the length of a rightmost branching chain
  //
  template <typename FeatClass, typename Feat_Count>
  static void tree_featurecount(FeatClass& fc, const sptree* tp, 
				Feat_Count& feat_count) {
    leftbranch_count(tp, 1, feat_count);
  }  // RightBranch::tree_featurecount()

  //! leftbranch_count() is called with the number of left branching
  //! nodes above this one
  //
  template <typename Feat_Count>
  static void leftbranch_count(const sptree* tp, int leftmost, Feat_Count& fc) {
    if (tp==NULL)
      return;
    else if (tp->is_punctuation())
      leftbranch_count(tp->next, leftmost, fc);
    else {
      if (tp->is_preterminal()) {
	assert(leftmost >= 1);
	int log2_leftmost = int(log2f(float(leftmost)));
	++fc[log2_leftmost];
      }
      else
	leftbranch_count(tp->child, leftmost+1, fc);
      leftbranch_count(tp->next, 1, fc);
    }
  }  // LeftBranchLength::leftbranch_count()

  // required types

  typedef int Feature;    // log2 length of right branch

  virtual const char* identifier() const {
    static char p[] = "LeftBranchLength";
    return p;
  }  // LeftBranchLength::identifier()

  SPFEATURES_COMMON_DEFINITIONS;
}; // LeftBranchLength{}


//! RightBranchLength is a feature whose value is the log of 
//! the length of the right-branching chain terminating in
//! each preterminal.
//!
//! Identifier is RightBranchLength
//
class RightBranchLength : public TreeFeatureClass {
public:

  //! tree_featurecound() counts the length of a rightmost branching chain
  //
  template <typename FeatClass, typename Feat_Count>
  static void tree_featurecount(FeatClass& fc, const sptree* tp, 
				Feat_Count& feat_count) {
    rightbranch_count(tp, 1, feat_count);
  }  // RightBranch::tree_featurecount()

  //! rightbranch_count() is called with the number of right branching
  //! nodes above this one
  //
  template <typename Feat_Count>
  static int rightbranch_count(const sptree* tp, int rightmost, Feat_Count& fc) {
    if (tp->next) 
      rightmost = rightbranch_count(tp->next, rightmost, fc);
    if (tp->is_punctuation())
      return rightmost;
    if (tp->is_preterminal()) {
      assert(rightmost >= 1);
      int log2_rightmost = int(log2f(float(rightmost)));
      ++fc[log2_rightmost];
    }
    else // tp->is_nonterminal()
      rightbranch_count(tp->child, rightmost+1, fc);
    return 1;
  }  // RightBranchLength::rightbranch_count()

  // required types

  typedef int Feature;    // log2 length of right branch

  virtual const char* identifier() const {
    static char p[] = "RightBranchLength";
    return p;
  }  // RightBranchLength::identifier()

  SPFEATURES_COMMON_DEFINITIONS;
}; // RightBranchLength{}


//! Heads is a feature of n levels of head-to-head dependencies.
//! Heads takes special care to follow head dependencies through
//! conjunctions.
//!
//! The identifier string is Heads:nheads:governorlex:dependentlex:headtype.
//
class Heads : public NodeFeatureClass {
public:

  typedef std::vector<symbol> Feature;

  enum head_type_type { syntactic, semantic };

  const size_type nheads;      //!< number of levels of heads to use
  const bool governorlex;   //!< use governor's word (in addition to its POS)
  const bool dependentlex;  //!< use dependent's head word (in addition its POS)
  const head_type_type head_type; //!< type of head dependency to track 
  std::string identifier_string;

  Heads(size_type nheads = 2,        //!< number of levels of heads to use
	bool governorlex = true,  //!< use governor's word (in addition to its POS)
	bool dependentlex = true, //!< use dependent's head word (in addition to its POS)
	head_type_type head_type = syntactic)
    : nheads(nheads), governorlex(governorlex), dependentlex(dependentlex),
      head_type(head_type), identifier_string("Heads:") 
  { 
    identifier_string += lexical_cast<std::string>(nheads) + ":";
    identifier_string += lexical_cast<std::string>(governorlex) + ":";
    identifier_string += lexical_cast<std::string>(dependentlex) + ":";
    identifier_string += lexical_cast<std::string>(head_type);
  }  // Heads::Heads()

  const sptree* headchild(const sptree* node) const {
    return head_type == semantic 
      ? node->label.semantic_headchild : node->label.syntactic_headchild;
  }  // Heads::headchild();

  //! node_featurecount() uses headchild() to find all of the heads
  //! of this node and its ancestors.
  //
  template <typename FeatClass, typename Feat_Count>
  void node_featurecount(FeatClass& fc, const sptree* node, 
			 Feat_Count& feat_count) 
  {
    if (!node->is_preterminal())  // only consider preterminal heads
      return;
    
    Feature f;
    f.push_back(node->label.cat);
    if (dependentlex)
      f.push_back(node->child->label.cat);
    
    visit_ancestors(feat_count, node, 1, f);
    assert(f.size() == (dependentlex ? 2 : 1));
  }  // Heads::node_featurecount()

  //! visit_ancestors() is written in continuation-passing style, in order
  //! to enumerate all possible governors.
  //
  template <typename Feat_Count>
  void visit_ancestors(Feat_Count& feat_count, const sptree* node,
		       size_type nsofar, Feature& f) {
    if (nsofar == nheads) {  // are we done?
      ++feat_count[f];
      return;
    }

    const sptree* ancestor = node->label.parent;
    if (ancestor == NULL)
      return;     // no more ancestors, so we can't find enough governors

    if (ancestor->is_coordination())    
      visit_ancestors(feat_count, ancestor, nsofar, f);  // skip this level
    else {
      const sptree* hchild = headchild(ancestor);
      if (hchild != NULL && node != hchild) 
	visit_descendants(feat_count, ancestor, nsofar, f, hchild);
      else
	visit_ancestors(feat_count, ancestor, nsofar, f);
    }
  }  // Heads::visit_ancestors()

  //! visit_descendants() collects the head(s) of head and then visits ancestors
  //
  template <typename Feat_Count>
  void visit_descendants(Feat_Count& feat_count, const sptree* ancestor,
			 size_type nsofar, Feature& f, const sptree* head)
  {
    if (head->is_preterminal()) {
      f.push_back(head->label.cat);      // push governor label
      if (governorlex)
	f.push_back(head->child->label.cat);
      visit_ancestors(feat_count, ancestor, nsofar+1, f);        // visit ancestors
      f.pop_back();   // pop governor
      if (governorlex)
	f.pop_back();
    }
    else {
      if (head->is_coordination()) {  // all children count as heads
	for (const sptree* child = head->child; child != NULL; child = child->next) 
	  if (child->label.cat == head->label.cat)
	    visit_descendants(feat_count, ancestor, nsofar, f, child);
      }
      else {    // visit head child
	const sptree* child = headchild(head);  
	if (child != NULL)
	  visit_descendants(feat_count, ancestor, nsofar, f, child);
      }
    }
  }  // Heads::visit_descendants()

  // Here is the stuff that every feature needs

  //! The identifier string is Heads:nheads:governorlex:dependentlex:headtype.
  //
  virtual const char *identifier() const {
    return identifier_string.c_str();
  }  // Heads::identifier()

  SPFEATURES_COMMON_DEFINITIONS;
};  // Heads{}



//! The PTsFeatureClass is an ABC for feature classes where the feature
//! count for a tree is the sum of feature counts for each node, and the
//! feature counts for each node depends on the local tree and its ancestors,
//! and the node's left and right string positions.
//!
//! Every subclass of PTsFeatureClass must define a method:
//!
//!  node_featurecount(fc, preterminals, tp, feat_count)
//
class PTsFeatureClass : public TreeFeatureClass {
public:

  typedef std::vector<const sptree*> SptreePtrs;

  template <typename FeatClass, typename Feat_Count>
  static void tree_featurecount(FeatClass& fc, const sptree* tp, 
				Feat_Count& feat_count) {
    assert(tp != NULL);
    SptreePtrs preterms;
    tp->preterminal_nodes(preterms, true);
    if (preterms.size() != tp->label.right) {
      std::cerr << "## preterms = " << preterms 
		<< "\n## tp = " << tp << std::endl;
      return;
    }
    assert(preterms.size() == tp->label.right);
    tree_featurecount(fc, preterms, tp, feat_count);
  }  // PTsFeatureClass:tree_featurecount()

  //! tree_featurecount() actually visits the nodes
  //
  template <typename FeatClass, typename Feat_Count>
  static void tree_featurecount(FeatClass& fc, const SptreePtrs& preterms,
				const sptree* tp, Feat_Count& feat_count)
  {
    fc.node_featurecount(fc, preterms, tp, feat_count);
    if (tp->is_nonterminal())
      tree_featurecount(fc, preterms, tp->child, feat_count);
    if (tp->next)
      tree_featurecount(fc, preterms, tp->next, feat_count);
  }  // PTsFeatureClass:tree_featurecount()
  
};  // PTsFeatureClass{}


//! The Neighbours{} includes the node's category, its binned length
//! and the left and right POS tags next to each node.  This version
//! has a bug in it -- use Edges() to accomplish the same thing w/out
//! the bug!
//!
//! Its identifier is Neighbours:<nleft>:<nright>
//
class Neighbours : public PTsFeatureClass {
public:

  Neighbours(size_type nleft = 0,   //!< include nleft left POS
	     size_type nright = 0)  //!< include nright right POS
    : nleft(nleft), nright(nright), identifier_string("Neighbours:")
  {
    (identifier_string += lexical_cast<std::string>(nleft)) += ":";
    identifier_string += lexical_cast<std::string>(nright);
  }  // Neighbours::Neighbours()
    		   
  // required types

  typedef std::pair<int,Ss> ISs;

  typedef ISs Feature;

  size_type nleft, nright;           // number of POS tags to left and right
  std::string identifier_string;  // will hold its identifier

  template <typename FeatClass, typename Feat_Count>
  void node_featurecount(FeatClass& fc, const SptreePtrs& preterms,
			 const sptree* node, Feat_Count& feat_count)
  {
    if (!node->is_nonterminal())
      return;

    size_type left = node->label.left;
    size_type right = node->label.right;

    Feature f;
    // number of preterminals
    f.first = quantize(right-left); 
    f.second.push_back(node->label.cat);    // category label

    // XXXX The following line is buggy, but is left in here because this
    // XXXX is what was used in the ACL'05 and CoNLL'05 talks
    //
    for (size_type i = 0; i < nleft; ++i)      // left preterminals
      f.second.push_back(i <= left 
			 ? preterms[left-i]->label.cat : endmarker());

    for (size_type i = 0; i < nright; ++i)	    // right preterminals
      f.second.push_back(right+i < preterms.size() 
			 ? preterms[right+i]->label.cat : endmarker());

    ++feat_count[f];
  }  // Neighbours::node_featurecount()
 
  virtual const char *identifier() const {
    return identifier_string.c_str();
  }  // Neighbours::identifier()

  SPFEATURES_COMMON_DEFINITIONS;
};  // Neighbours{}

//! The Edges{} includes the node's category, its binned length
//! and the left and right POS preceding and following the constituent edges
//!
//! Its identifier is Edges:<binnedlength>:<nleftprec>:<nleftsucc>:<nrightprec>:<nrightsucc>
//
class Edges : public PTsFeatureClass {
public:

  Edges(bool binned_length = false,  //!< include binned length
	size_type nleftprec = 0,     //!< include nleft left preceding POS
	size_type nleftsucc = 0,     //!< include nleft left following POS
	size_type nrightprec = 0,    //!< include nright right preceding POS
	size_type nrightsucc = 0)    //!< include nright right following POS
    : binned_length(binned_length), nleftprec(nleftprec), nleftsucc(nleftsucc),
      nrightprec(nrightprec), nrightsucc(nrightsucc), identifier_string("Edges:")
  {
    (identifier_string += lexical_cast<std::string>(binned_length)) += ":";
    (identifier_string += lexical_cast<std::string>(nleftprec)) += ":";
    (identifier_string += lexical_cast<std::string>(nleftsucc)) += ":";
    (identifier_string += lexical_cast<std::string>(nrightprec)) += ":";
    identifier_string += lexical_cast<std::string>(nrightsucc);
  }  // Edges::Edges()
    		   
  // required types

  typedef Ss Feature;

  bool binned_length;             // collect binned length
  size_type nleftprec, nleftsucc, nrightprec, nrightsucc;  // number of POS surrounding edges
  std::string identifier_string;  // will hold its identifier

  template <typename FeatClass, typename Feat_Count>
  void node_featurecount(FeatClass& fc, const SptreePtrs& preterms,
			 const sptree* node, Feat_Count& feat_count)
  {
    if (!node->is_nonterminal())
      return;

    size_type left = node->label.left;
    size_type right = node->label.right;
    size_type nwords = preterms.size();

    Feature f;
    if (binned_length)
      f.push_back(symbol_quantize(right-left)); // number of preterminals
    f.push_back(node->label.cat);               // category label

    for (size_type i = 1; i <= nleftprec; ++i)
      f.push_back(i <= left
		  ? preterms[left-i]->label.cat : endmarker());

    for (size_type i = 0; i < nleftsucc; ++i)
      f.push_back(left+i < nwords 
		  ? preterms[left+i]->label.cat : endmarker());
    
    for (size_type i = 1; i <= nrightprec; ++i)
      f.push_back(i <= right
		  ? preterms[right-i]->label.cat : endmarker());

    for (size_type i = 0; i < nrightsucc; ++i)	    // right preterminals
      f.push_back(right+i < nwords 
		  ? preterms[right+i]->label.cat : endmarker());

    ++feat_count[f];
  }  // Edges::node_featurecount()
 
  virtual const char *identifier() const {
    return identifier_string.c_str();
  }  // Edges::identifier()

  SPFEATURES_COMMON_DEFINITIONS;
};  // Edges{}

//! The WordNeighbours{} includes the node's category, its binned length
//! and the left and right words next to each node.
//!
//! Its identifier is WordNeighbours:<binnedlengthflag>:<nleft>:<nright>
//
class WordNeighbours : public PTsFeatureClass {
public:

  WordNeighbours(bool binned_length = false,  //!< include binned length
		 size_type nleft = 0,         //!< include nleft left words
		 size_type nright = 0)        //!< include nright right words
    : binned_length(binned_length), nleft(nleft), nright(nright), 
    identifier_string("WordNeighbours:")
  {
    (identifier_string += lexical_cast<std::string>(binned_length)) += ":";
    (identifier_string += lexical_cast<std::string>(nleft)) += ":";
    identifier_string += lexical_cast<std::string>(nright);
  }  // WordNeighbours::WordNeighbours()
    		   
  // required types

  typedef Ss Feature;

  bool binned_length;             // collect binned length
  size_type nleft, nright;        // number of words to left and right
  std::string identifier_string;  // will hold its identifier

  template <typename FeatClass, typename Feat_Count>
  void node_featurecount(FeatClass& fc, const SptreePtrs& preterms,
			 const sptree* node, Feat_Count& feat_count)
  {
    if (!node->is_nonterminal())
      return;

    size_type left = node->label.left;
    size_type right = node->label.right;

    Feature f;
    if (binned_length)
      f.push_back(symbol_quantize(right-left)); // number of preterminals
    f.push_back(node->label.cat);               // category label

    //  XXXXX BUG XXXXX  -- should be
    // for (size_type i = 1; i <= nleft; ++i)
    for (size_type i = 0; i < nleft; ++i)       // left preterminals
      f.push_back(i <= left 
		  ? preterms[left-i]->child->label.cat : endmarker());

    for (size_type i = 0; i < nright; ++i)	    // right preterminals
      f.push_back(right+i < preterms.size() 
		  ? preterms[right+i]->child->label.cat : endmarker());

    ++feat_count[f];
  }  // WordNeighbours::node_featurecount()
 
  virtual const char *identifier() const {
    return identifier_string.c_str();
  }  // WordNeighbours::identifier()

  SPFEATURES_COMMON_DEFINITIONS;
};  // WordNeighbours{}


//! The WordEdges{} includes the node's category, its binned length
//! and the left and right words preceding and following the constituent edges
//!
//! Its identifier is WordEdges:<binnedlength>:<nleftprec>:<nleftsucc>:<nrightprec>:<nrightsucc>
//
class WordEdges : public PTsFeatureClass {
public:

  WordEdges(bool binned_length = false,  //!< include binned length
	    size_type nleftprec = 0,     //!< include nleft left preceding words
	    size_type nleftsucc = 0,     //!< include nleft left following words
	    size_type nrightprec = 0,    //!< include nright right preceding words
	    size_type nrightsucc = 0)    //!< include nright right following words
    : binned_length(binned_length), nleftprec(nleftprec), nleftsucc(nleftsucc),
      nrightprec(nrightprec), nrightsucc(nrightsucc), identifier_string("WordEdges:")
  {
    (identifier_string += lexical_cast<std::string>(binned_length)) += ":";
    (identifier_string += lexical_cast<std::string>(nleftprec)) += ":";
    (identifier_string += lexical_cast<std::string>(nleftsucc)) += ":";
    (identifier_string += lexical_cast<std::string>(nrightprec)) += ":";
    identifier_string += lexical_cast<std::string>(nrightsucc);
  }  // WordEdges::WordEdges()
    		   
  // required types

  typedef Ss Feature;

  bool binned_length;             // collect binned length
  size_type nleftprec, nleftsucc, nrightprec, nrightsucc;  // number of words surrounding edges
  std::string identifier_string;  // will hold its identifier

  template <typename FeatClass, typename Feat_Count>
  void node_featurecount(FeatClass& fc, const SptreePtrs& preterms,
			 const sptree* node, Feat_Count& feat_count)
  {
    if (!node->is_nonterminal())
      return;

    size_type left = node->label.left;
    size_type right = node->label.right;
    size_type nwords = preterms.size();

    Feature f;
    if (binned_length)
      f.push_back(symbol_quantize(right-left)); // number of preterminals
    f.push_back(node->label.cat);               // category label

    for (size_type i = 1; i <= nleftprec; ++i)
      f.push_back(i <= left
		  ? preterms[left-i]->child->label.cat : endmarker());

    for (size_type i = 0; i < nleftsucc; ++i)
      f.push_back(left+i < nwords 
		  ? preterms[left+i]->child->label.cat : endmarker());
    
    for (size_type i = 1; i <= nrightprec; ++i)
      f.push_back(i <= right
		  ? preterms[right-i]->child->label.cat : endmarker());

    for (size_type i = 0; i < nrightsucc; ++i)	    // right preterminals
      f.push_back(right+i < nwords 
		  ? preterms[right+i]->child->label.cat : endmarker());

    ++feat_count[f];
  }  // WordEdges::node_featurecount()
 
  virtual const char *identifier() const {
    return identifier_string.c_str();
  }  // WordEdges::identifier()

  SPFEATURES_COMMON_DEFINITIONS;
};  // WordEdges{}


//! The Heavy{} classifies nodes by their size and 
//! how close to the end of the sentence they occur, as well as whether
//! they are followed by punctuation or coordination.
//
class Heavy : public PTsFeatureClass {
public:

  typedef std::pair<Is,Ss> Feature;

  template <typename FeatClass, typename Feat_Count>
  void node_featurecount(FeatClass& fc, const SptreePtrs& preterms,
			 const sptree* node, Feat_Count& feat_count)
  {
    if (!node->is_nonterminal())
      return;

    symbol final_punct = endmarker();
    symbol following_punct = endmarker();

    assert(node->label.right > 0);
    assert(node->label.right <= preterms.size());

    if (preterms[node->label.right-1]->is_punctuation())
      final_punct = preterms[node->label.right-1]->child->label.cat;

    if (node->label.right < preterms.size() 
	&& preterms[node->label.right]->is_punctuation())
      following_punct = preterms[node->label.right]->child->label.cat;

    Feature f;
    // number of preterminals
    f.first.push_back(quantize(node->label.right-node->label.left));
    f.first.push_back(quantize(preterms.size()-node->label.right));      // how far from end
    f.second.push_back(node->label.cat);     // category label
    f.second.push_back(final_punct);
    f.second.push_back(following_punct);

    ++feat_count[f];
  }  // Heavy::node_featurecount()

  virtual const char *identifier() const {
    return "Heavy";
  }  // Heavy::identifier()

  SPFEATURES_COMMON_DEFINITIONS;
};  // Heavy{}


//! NGramTree identifies n-gram tree fragments.  The identifier is
//!
//! NGramTree:ngram:lexicalize:collapse:nancs
//
class NGramTree : public TreeFeatureClass {
public:

  // required types

  typedef sstring Feature;

  enum lexicalize_type { none, closed_class, functional, all };

  int ngram;                      //!< # of words in context
  lexicalize_type lexicalize;     //!< lexicalize preterminals
  bool collapse;                  //!< collapse nodes not dominating ngram
  int nancs;                      //!< extra ancestors to go up
  std::string identifier_string;  //!< returned by identifier()

  NGramTree(int ngram = 2, lexicalize_type lexicalize = none, bool collapse = false,
	    int nancs = 0) 
    : ngram(ngram), lexicalize(lexicalize), collapse(collapse), nancs(nancs),
      identifier_string("NGramTree:") 
  { 
    identifier_string += lexical_cast<std::string>(ngram) + ":";
    identifier_string += lexical_cast<std::string>(lexicalize) + ":";
    identifier_string += lexical_cast<std::string>(collapse) + ":";
    identifier_string += lexical_cast<std::string>(nancs);
  }  // NGramTree::NGramTree()

  tree* selective_copy(const sptree* sp, size_type left, size_type right, 
		       bool copy_next = false) 
  {
    const sptree_label& label = sp->label;

    if (collapse) 
      if (label.right <= left) 
	return (sp->next && copy_next) 
	  ? selective_copy(sp->next, left, right, copy_next) : NULL;
      else if (label.left >= right)
	return NULL;

    tree* t = new tree(label);
    if (sp->child && label.left < right && label.right > left
	&& (sp->is_nonterminal()
	    || lexicalize == all
	    || (lexicalize == functional && sp->is_functional())
	    || (lexicalize == closed_class && sp->is_closed_class())))
      t->child = selective_copy(sp->child, left, right, true);

    if (copy_next && sp->next)
      t->next = selective_copy(sp->next, left, right, copy_next);

    return t;
  }  // NGramTree::selective_copy()

  template <typename FeatClass, typename Feat_Count>
  void tree_featurecount(FeatClass& fc, const sptree* root, 
			 Feat_Count& feat_count) {
    if (debug_level >= 10000)
      std::cerr << "# root = " << root << std::endl;
    std::vector<const sptree*> preterms;
    root->preterminal_nodes(preterms);
    for (size_type i = 0; i + ngram < preterms.size(); ++i) {
      const sptree* t0;
      for (t0 = preterms[i]; t0 != NULL && t0->label.right < i + ngram; 
	   t0 = t0->label.parent)
	;

      assert(t0 != NULL);

      for (int ianc = 0; ianc < nancs && t0; ++ianc)
	t0 = t0->label.parent;   // go up extra ancestors

      if (t0 == NULL)
	return;

      tree* frag = selective_copy(t0, i, i + ngram);
      Feature feat(frag);
      if (debug_level >= 20000)
	std::cerr << "#  " << preterms[i]->child->label.cat 
		  << ": " << feat << std::endl;
      ++feat_count[feat];
      delete frag;
    }
  }  // NGramTree::tree_featurecount()
 
  virtual const char *identifier() const {
    return identifier_string.c_str();
  }  // NGramTree::identifier()

  SPFEATURES_COMMON_DEFINITIONS;
};  // NGramTree{}


//! HeadTree
//!
//! Identifier is HeadTree:collapse:lexicalize:nancs:headtype
//
class HeadTree : public NodeFeatureClass {
public:

  // required types

  typedef sstring Feature;

  enum head_type { syntactic, semantic };

  bool collapse;                 //!< collapse nodes not dominating ngram
  bool lexicalize;		 //!< include lexical item
  int nancs;                     //!< extra ancestors to go up
  head_type htype;               //!< type of heads to project
  std::string identifier_string; //!< returned by identifier()

  HeadTree(bool collapse = true, bool lexicalize = false, 
	   int nancs = 0, head_type htype = semantic) 
    : collapse(collapse), lexicalize(lexicalize), nancs(nancs), htype(htype),
      identifier_string("HeadTree:") 
  { 
    identifier_string += lexical_cast<std::string>(collapse) + ":";
    identifier_string += lexical_cast<std::string>(lexicalize) + ":";
    identifier_string += lexical_cast<std::string>(nancs) + ":";
    identifier_string += lexical_cast<std::string>(htype);
  }  // HeadTree::HeadTree()

  tree* selective_copy(const sptree* sp, unsigned int headleft) 
  {
    if (!sp)
      return NULL;

    const sptree_label& label = sp->label;

    if (collapse) {
      unsigned int left = label.previous ? label.previous->label.left : label.left;
      unsigned int right = sp->next ? sp->next->label.right : label.right;
      if (right <= headleft) 
	return selective_copy(sp->next, headleft);
      else if (left > headleft)
	return NULL;
    }

    return new tree(label,
		    (sp->is_nonterminal() || (lexicalize && label.left == headleft)) 
		    ? selective_copy(sp->child, headleft) : NULL,
		    selective_copy(sp->next, headleft));
  }  // HeadTree::selective_copy()

  template <typename FeatClass, typename Feat_Count>
  void tree_featurecount(FeatClass& fc, const sptree* root, 
			 Feat_Count& feat_count) {
    if (debug_level >= 20000)
      std::cerr << "# root = " << root << std::endl;
    std::vector<const sptree*> preterms;
    root->preterminal_nodes(preterms);
    for (size_type i = 0; i < preterms.size(); ++i) {
      const sptree* t0 = preterms[i];
      while (true) {
	const sptree* parent = t0->label.parent;
	if (!parent)
	  break;
	const sptree* hchild  = (htype == syntactic) 
	  ? parent->label.syntactic_headchild
	  : parent->label.semantic_headchild;
	if (hchild != t0)
	  break;
	t0 = parent;
      }

      assert(t0 != NULL);

      for (int ianc = 0; ianc < nancs && t0; ++ianc)
	t0 = t0->label.parent;   // go up extra ancestors

      if (t0 == NULL)
	return;

      tree* frag = selective_copy(t0, i);
      Feature feat(frag);
      if (debug_level >= 20000)
	std::cerr << "#  " << preterms[i]->child->label.cat 
		  << ": " << feat << std::endl;
      ++feat_count[feat];
      delete frag;
    }
  }  // HeadTree::tree_featurecount()
 
  virtual const char *identifier() const {
    return identifier_string.c_str();
  }  // HeadTree::identifier()

  SPFEATURES_COMMON_DEFINITIONS;
};  // HeadTree{}


class SubjVerbAgr : public NodeFeatureClass {
public:

  typedef Ss Feature;

  template <typename FeatClass, typename Feat_Count>
  void node_featurecount(FeatClass& fc, const sptree* node, 
			 Feat_Count& feat_count) 
  {
    if ((node->label.cat != S() && node->label.cat != SINV()) 
	|| node->label.syntactic_lexhead == NULL)
      return;
    
    const sptree* subject = NULL;

    // subject is last NP before VP

    for (const sptree* child = node->child; child != NULL; child = child->next) 
      if (child->label.cat == NP())
	subject = child;
      else if (child->label.cat == VP())
	break;

    if (subject == NULL || subject->label.semantic_lexhead == NULL)
      return;
    
    Feature f;
    f.push_back(subject->label.semantic_lexhead->label.cat);
    f.push_back(node->label.syntactic_lexhead->label.cat);
    ++feat_count[f];
  }  // SubjVerbAgr::node_featurecount()

  virtual const char *identifier() const {
    return "SubjVerbAgr";
  }  // SubjVerbAgr::identifier()

  SPFEATURES_COMMON_DEFINITIONS;
};  // SubjVerbAgr{}

class SynSemHeads : public NodeFeatureClass {
public:

  typedef Ss Feature;

  enum annotation_type { none, lex_syn, lex_all };
  annotation_type ann;
  std::string identifier_string; //!< identifier string, returned by identifier()
  
  SynSemHeads(annotation_type ann = none) 
    : ann(ann), identifier_string("SynSemHeads:")
  {
    identifier_string += lexical_cast<std::string>(ann);
  }  // SynSemHeads::SynSemHeads()

  template <typename FeatClass, typename Feat_Count>
  void node_featurecount(FeatClass& fc, const sptree* node, 
			 Feat_Count& feat_count) 
  {
    const sptree_label& label = node->label;

    if (label.syntactic_lexhead == label.semantic_lexhead)
      return;

    Feature f;
    f.push_back(label.syntactic_lexhead ? label.syntactic_lexhead->label.cat : endmarker());
    if (ann != none) {
      if (label.syntactic_lexhead == NULL)
	return;
      else
	f.push_back(label.syntactic_lexhead->child->label.cat);
    }

    f.push_back(label.semantic_lexhead ? label.semantic_lexhead->label.cat : endmarker());

    if (ann == lex_all) {
      if (label.semantic_lexhead == NULL)
	return;
      else
	f.push_back(label.semantic_lexhead->child->label.cat);
    }
    ++feat_count[f];
  }  // SynSemHeads::node_featurecount()

  virtual const char *identifier() const {
    return identifier_string.c_str();
  }  // SynSemHeads::identifier()

  SPFEATURES_COMMON_DEFINITIONS;
};  // SynSemHeads{}


//////////////////////////////////////////////////////////////////////////
//                                                                      //
//                        Coordination features                         //
//                                                                      //
//////////////////////////////////////////////////////////////////////////


//! CoPar{} counts the number of parallel and non-parallel coordinations
//! at various levels
//!
//! Identifier is CoPar:IgnorePreterms
//
class CoPar : public NodeFeatureClass {
  bool ignore_preterms;
  std::string identifier_string;

public:

  CoPar(bool ignore_preterms = false) 
    : ignore_preterms(ignore_preterms), identifier_string("CoPar:")
  {
    identifier_string += lexical_cast<std::string>(ignore_preterms);
  }  // CoPar::CoPar()


  template <typename FeatClass, typename Feat_Count>
  void node_featurecount(FeatClass& fc, const sptree* node, 
			 Feat_Count& feat_count) 
  {
    if (!node->is_coordination())
      return;
    for (int depth = 1; depth <= 5; ++depth) {
      const sptree* last_child = NULL;
      for (const sptree* child = node->child; child; child = child->next) {
	if (child->is_punctuation() || child->is_conjunction())
	  continue;
	if (last_child != NULL) {
	  int m = match(depth, last_child, child);
	  if (m != -1)
	    ++feat_count[Feature(depth,m)];
	}
	last_child = child;
      }
    }
  }  // CoPar::node_feature_count()


  //! match() returns 1 if node1 and node2 match to depth, 0 if they mismatch
  //! and -1 if they match but do not have any subnodes at depth.
  //
  int match(int depth, const sptree* node1, const sptree* node2) const {
    assert(node1 != NULL);
    assert(node2 != NULL);
    if (node1->label.cat != node2->label.cat)
      return 0;
    if (depth == 1)
      return 1;
    if (node1->is_preterminal()) {
      assert(node2->is_preterminal());
      return -1;
    }
    return matches(depth-1, node1->child, node2->child);
  }

  //! matches() is responsible for matching node1 and node2 and their right
  //! siblings
  //
  int matches(int depth, const sptree* node1, const sptree* node2) const {
    assert(depth >= 1);

    if (ignore_preterms) {
      while (node1 != NULL && node1->is_preterminal())
	node1 = node1->next;
      while (node2 != NULL && node2->is_preterminal())
	node2 = node2->next;
    }

    if (node1 == NULL) 
      return (node2 == NULL) ? -1 : 0;
    
    if (node2 == NULL)
      return 0;
    
    int m1 = match(depth, node1, node2);
    int m2 = matches(depth, node1->next, node2->next);
    
    if (m1 == 0 || m2 == 0)
      return 0;
    else if (m1 == 1 || m2 == 1)
      return 1;
    else
      return -1;
  }

  virtual const char* identifier() const {
    return identifier_string.c_str();
  }  // CoPar::identifier()

  typedef std::pair<int,int> Feature;

  SPFEATURES_COMMON_DEFINITIONS;
};


//! CoLenPar{} counts the number of adjacent conjuncts that have
//!  the same length, are shorter, and are longer.
//
class CoLenPar : public NodeFeatureClass {
public:

  template <typename FeatClass, typename Feat_Count>
  void node_featurecount(FeatClass& fc, const sptree* node, 
			 Feat_Count& feat_count) 
  {
    if (!node->is_coordination())
      return;
    const sptree* last_child = NULL;
    int last_size = 0;
    for (const sptree* child = node->child; child; child = child->next) {
      if (child->is_punctuation() || child->is_conjunction())
	continue;
      int size = child->label.right - child->label.left;
      if (last_child != NULL) {
	int dsize = size - last_size;
	if (dsize > 4)
	  dsize = 5;
	else if (dsize < -4)
	  dsize = -5;
	++feat_count[Feature(dsize,child->next==NULL)];
      }
      last_child = child;
      last_size = size;
    }
  }  // CoLenPar::node_feature_count()

  virtual const char* identifier() const {
    return "CoLenPar";
  }  // CoLenPar::identifier()

  typedef std::pair<int,int> Feature;

  SPFEATURES_COMMON_DEFINITIONS;
};

inline void FeatureClassPtrs::features_connll() {
  push_back(new NLogP());

  push_back(new Rule());
  push_back(new Rule(0, 1));
  push_back(new Rule(0, 0, Rule::noroot));
  push_back(new Rule(0, 0, Rule::noroot, true));
  push_back(new Rule(0, 0, Rule::noroot, false, Rule::lexical));
  push_back(new Rule(0, 0, Rule::noroot, false, Rule::none, Rule::lexical));
  push_back(new Rule(0, 0, Rule::noroot, false, Rule::lexical, Rule::lexical));

  push_back(new NGram(1, 1, NGram::noroot, true));
  push_back(new NGram(2, 1, NGram::rootonly, true));
  push_back(new NGram(3, 1, NGram::rootonly, true));
  push_back(new NGram(2, 1, NGram::noroot, false, NGram::lexical));
  push_back(new NGram(2, 1, NGram::noroot, false, NGram::none, NGram::lexical));

  push_back(new Word(1));
  push_back(new Word(2));

  push_back(new WProj());

  push_back(new RightBranch());

  push_back(new Heavy());

  push_back(new NGramTree(2, NGramTree::none, true));
  push_back(new NGramTree(2, NGramTree::all, true));
  push_back(new NGramTree(3, NGramTree::functional, true));

  push_back(new HeadTree(true, false, 0, HeadTree::syntactic));
  push_back(new HeadTree(true, false, 0, HeadTree::semantic));
  push_back(new HeadTree(true, true, 0, HeadTree::semantic));
  
  push_back(new Heads(2, false, false, Heads::syntactic));
  push_back(new Heads(2, true, true, Heads::syntactic));
  push_back(new Heads(2, true, true, Heads::semantic));
  push_back(new Heads(3, false, false));

  push_back(new Neighbours(0,0));
  push_back(new Neighbours(0,1));
  push_back(new Neighbours(1,0));

  push_back(new CoPar(false));

  push_back(new CoLenPar());

} // FeatureClassPtrs::features_connll()

/*
inline void FeatureClassPtrs::features_connll_sub() {
  push_back(new NLogCondProb());

  push_back(new Rule());
  push_back(new Rule(0, 1));
  push_back(new Rule(0, 0, true));
  push_back(new Rule(0, 0, false, true));
  push_back(new Rule(0, 0, false, false, Rule::lexical));
  push_back(new Rule(0, 0, false, false, Rule::none, Rule::lexical));
  push_back(new Rule(0, 0, false, false, Rule::lexical, Rule::lexical));

  push_back(new NGram(1, 1, false, true));
  push_back(new NGram(2, 1, true, true));
  push_back(new NGram(3, 1, true, true));
  push_back(new NGram(2, 1, false, false, NGram::lexical));
  push_back(new NGram(2, 1, false, false, NGram::none, NGram::lexical));

  push_back(new Word(1));
  push_back(new Word(2));

  push_back(new WProj());

  push_back(new RightBranch());

  push_back(new Heavy());

  push_back(new NGramTree(2, NGramTree::none, true));
  push_back(new NGramTree(2, NGramTree::all, true));
  push_back(new NGramTree(3, NGramTree::functional, true));

  // push_back(new HeadTree(true, false, 0, HeadTree::syntactic));
  push_back(new HeadTree(true, false, 0, HeadTree::semantic));
  push_back(new HeadTree(true, true, 0, HeadTree::semantic));
  
  push_back(new Heads(2, false, false, Heads::syntactic));
  // push_back(new Heads(2, true, true, Heads::syntactic));
  push_back(new Heads(2, true, true, Heads::semantic));
  push_back(new Heads(3, false, false));

  // push_back(new Neighbours(0,0));
  push_back(new Neighbours(0,1));
  push_back(new Neighbours(1,0));

  push_back(new CoPar(false));

  push_back(new CoLenPar());

} // FeatureClassPtrs::features_connll_sub()
*/

inline void FeatureClassPtrs::features_conj() {
  push_back(new NLogCondProb());
  push_back(new CoPar(false));
  push_back(new CoPar(true));
  push_back(new CoLenPar());
}  // FeatureClassPtrs::features_conj()



inline void FeatureClassPtrs::features_dp_27Aug05() {
  push_back(new NLogP());

  push_back(new WordNeighbours(false, 0,0));
  push_back(new WordNeighbours(false, 0,1));
  push_back(new WordNeighbours(false, 0,2));
  push_back(new WordNeighbours(false, 1,0));
  push_back(new WordNeighbours(false, 2,0));
  push_back(new WordNeighbours(false, 1,1));
  push_back(new WordNeighbours(false, 1,2));
  push_back(new WordNeighbours(false, 2,1));
  push_back(new WordNeighbours(false, 2,2));

  push_back(new WordNeighbours(true, 0,0));
  push_back(new WordNeighbours(true, 0,1));
  push_back(new WordNeighbours(true, 0,2));
  push_back(new WordNeighbours(true, 1,0));
  push_back(new WordNeighbours(true, 2,0));
  push_back(new WordNeighbours(true, 1,1));
  push_back(new WordNeighbours(true, 1,2));
  push_back(new WordNeighbours(true, 2,1));
  push_back(new WordNeighbours(true, 2,2));

}  // FeatureClassPtrs::features_dp_27Aug05()

inline void FeatureClassPtrs::features_dp_31Aug05() {
  push_back(new NLogP());

  size_type maxwidth = 1;

  for (size_type binflag = 0; binflag < 2; ++binflag)
    for (size_type nleftprec = 0; nleftprec <= maxwidth; ++nleftprec)
      for (size_type nleftsucc = 0; nleftsucc <= maxwidth; ++nleftsucc)
	for (size_type nrightprec = 0; nrightprec <= maxwidth; ++nrightprec)
	  for (size_type nrightsucc = 0; nrightsucc <= maxwidth; ++nrightsucc)
	    push_back(new WordEdges(binflag, nleftprec, nleftsucc, nrightprec, nrightsucc));

}  // FeatureClassPtrs::features_dp_31Aug05()

inline void FeatureClassPtrs::features_050902() {
  push_back(new NLogP());

  push_back(new Rule());
  push_back(new Rule(0, 1));
  push_back(new Rule(0, 0, Rule::rootonly));
  push_back(new Rule(0, 0, Rule::noroot, true));
  push_back(new Rule(0, 0, Rule::noroot, false, Rule::lexical));
  push_back(new Rule(0, 0, Rule::noroot, false, Rule::none, Rule::lexical));
  push_back(new Rule(0, 0, Rule::noroot, false, Rule::lexical, Rule::lexical));

  push_back(new NGram(1, 1, NGram::noroot, true));
  push_back(new NGram(2, 1, NGram::rootonly, true));
  push_back(new NGram(3, 1, NGram::rootonly, true));
  push_back(new NGram(2, 1, NGram::noroot, false, NGram::lexical));
  push_back(new NGram(2, 1, NGram::noroot, false, NGram::none, NGram::lexical));

  push_back(new Word(1));
  push_back(new Word(2));

  push_back(new WProj());

  push_back(new RightBranch());

  push_back(new Heavy());

  push_back(new NGramTree(2, NGramTree::none, true));
  push_back(new NGramTree(2, NGramTree::all, true));
  push_back(new NGramTree(3, NGramTree::functional, true));

  push_back(new HeadTree(true, false, 0, HeadTree::syntactic));
  push_back(new HeadTree(true, false, 0, HeadTree::semantic));
  push_back(new HeadTree(true, true, 0, HeadTree::semantic));
  
  push_back(new Heads(2, false, false, Heads::syntactic));
  push_back(new Heads(2, true, true, Heads::syntactic));
  push_back(new Heads(2, true, true, Heads::semantic));
  push_back(new Heads(3, false, false));

  push_back(new CoPar(false));

  push_back(new CoLenPar());

  size_type maxwidth = 2, maxsumwidth = 2;

  for (size_type binflag = 0; binflag < 2; ++binflag)
    for (size_type nleftprec = 0; nleftprec <= maxwidth; ++nleftprec)
      for (size_type nleftsucc = 0; nleftsucc <= maxwidth; ++nleftsucc)
	for (size_type nrightprec = 0; nrightprec <= maxwidth; ++nrightprec)
	  for (size_type nrightsucc = 0; nrightsucc <= maxwidth; ++nrightsucc)
	    if (nleftprec + nleftsucc + nrightprec + nrightsucc <= maxsumwidth)
	      push_back(new Edges(binflag, nleftprec, nleftsucc, nrightprec, nrightsucc));

  for (size_type binflag = 0; binflag < 2; ++binflag)
    for (size_type nleftprec = 0; nleftprec <= maxwidth; ++nleftprec)
      for (size_type nleftsucc = 0; nleftsucc <= maxwidth; ++nleftsucc)
	for (size_type nrightprec = 0; nrightprec <= maxwidth; ++nrightprec)
	  for (size_type nrightsucc = 0; nrightsucc <= maxwidth; ++nrightsucc)
	    if (nleftprec + nleftsucc + nrightprec + nrightsucc <= maxsumwidth)
	      push_back(new WordEdges(binflag, nleftprec, nleftsucc, nrightprec, nrightsucc));

}  // FeatureClassPtrs::features_050902()


inline void FeatureClassPtrs::features_050904() {
  push_back(new NLogP());

  push_back(new Rule());
  push_back(new Rule(0, 1));
  push_back(new Rule(0, 0, Rule::rootonly));
  push_back(new Rule(0, 0, Rule::noroot, true));
  push_back(new Rule(0, 0, Rule::noroot, false, Rule::lexical));
  push_back(new Rule(0, 0, Rule::noroot, false, Rule::none, Rule::lexical));
  push_back(new Rule(0, 0, Rule::noroot, false, Rule::lexical, Rule::lexical));

  push_back(new NGram(1, 1, NGram::noroot, true));
  push_back(new NGram(2, 1, NGram::rootonly, true));
  push_back(new NGram(3, 1, NGram::rootonly, true));
  push_back(new NGram(2, 1, NGram::noroot, false, NGram::lexical));
  push_back(new NGram(2, 1, NGram::noroot, false, NGram::none, NGram::lexical));

  push_back(new Word(1));
  push_back(new Word(2));

  push_back(new WProj());

  push_back(new RightBranch());

  push_back(new Heavy());

  push_back(new NGramTree(2, NGramTree::none, true));
  push_back(new NGramTree(2, NGramTree::all, true));
  push_back(new NGramTree(3, NGramTree::functional, true));

  push_back(new HeadTree(true, false, 0, HeadTree::syntactic));
  push_back(new HeadTree(true, false, 0, HeadTree::semantic));
  push_back(new HeadTree(true, true, 0, HeadTree::semantic));
  
  push_back(new Heads(2, false, false, Heads::syntactic));
  push_back(new Heads(2, true, true, Heads::syntactic));
  push_back(new Heads(2, true, true, Heads::semantic));
  push_back(new Heads(3, false, false));

  push_back(new CoPar(false));

  push_back(new CoLenPar());

  size_type maxwidth = 2, maxsumwidth = 2;

  for (size_type binflag = 0; binflag < 2; ++binflag)
    for (size_type nleftprec = 0; nleftprec <= maxwidth; ++nleftprec)
      for (size_type nleftsucc = 0; nleftsucc <= maxwidth; ++nleftsucc)
	for (size_type nrightprec = 0; nrightprec <= maxwidth; ++nrightprec)
	  for (size_type nrightsucc = 0; nrightsucc <= maxwidth; ++nrightsucc)
	    if (nleftprec + nleftsucc + nrightprec + nrightsucc <= maxsumwidth)
	      push_back(new Edges(binflag, nleftprec, nleftsucc, nrightprec, nrightsucc));
}  // FeatureClassPtrs::features_050904()


inline void FeatureClassPtrs::features_context0() {
  push_back(new NLogP());
  push_back(new Rule(0, 0, Rule::lastroottype));
}  // FeatureClassPtrs::features_context0()



//! FeatureClassPtrs::FeatureClassPtrs() preloads a
//! set of features.
//
inline FeatureClassPtrs::FeatureClassPtrs() {
  // features_connll();
  features_050902(); 
  // features_context0();
} // FeatureClassPtrs::FeatureClassPtrs()
  

#undef FloatTol

#endif // SPFEATURES_H