Location: LEMON/LEMON-official/lemon/lgf_reader.h

Load file history
gravatar
alpar (Alpar Juttner)
Merge bugfix #420
   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
/* -*- mode: C++; indent-tabs-mode: nil; -*-
*
* This file is a part of LEMON, a generic C++ optimization library.
*
* Copyright (C) 2003-2010
* Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
* (Egervary Research Group on Combinatorial Optimization, EGRES).
*
* Permission to use, modify and distribute this software is granted
* provided that this copyright notice appears in all copies. For
* precise terms see the accompanying LICENSE file.
*
* This software is provided "AS IS" with no warranty of any kind,
* express or implied, and with no claim as to its suitability for any
* purpose.
*
*/
///\ingroup lemon_io
///\file
///\brief \ref lgf-format "LEMON Graph Format" reader.
#ifndef LEMON_LGF_READER_H
#define LEMON_LGF_READER_H
#include <iostream>
#include <fstream>
#include <sstream>
#include <set>
#include <map>
#include <lemon/core.h>
#include <lemon/lgf_writer.h>
#include <lemon/concept_check.h>
#include <lemon/concepts/maps.h>
namespace lemon {
namespace _reader_bits {
template <typename Value>
struct DefaultConverter {
Value operator()(const std::string& str) {
std::istringstream is(str);
Value value;
if (!(is >> value)) {
throw FormatError("Cannot read token");
}
char c;
if (is >> std::ws >> c) {
throw FormatError("Remaining characters in token");
}
return value;
}
};
template <>
struct DefaultConverter<std::string> {
std::string operator()(const std::string& str) {
return str;
}
};
template <typename _Item>
class MapStorageBase {
public:
typedef _Item Item;
public:
MapStorageBase() {}
virtual ~MapStorageBase() {}
virtual void set(const Item& item, const std::string& value) = 0;
};
template <typename _Item, typename _Map,
typename _Converter = DefaultConverter<typename _Map::Value> >
class MapStorage : public MapStorageBase<_Item> {
public:
typedef _Map Map;
typedef _Converter Converter;
typedef _Item Item;
private:
Map& _map;
Converter _converter;
public:
MapStorage(Map& map, const Converter& converter = Converter())
: _map(map), _converter(converter) {}
virtual ~MapStorage() {}
virtual void set(const Item& item ,const std::string& value) {
_map.set(item, _converter(value));
}
};
template <typename _GR, bool _dir, typename _Map,
typename _Converter = DefaultConverter<typename _Map::Value> >
class GraphArcMapStorage : public MapStorageBase<typename _GR::Edge> {
public:
typedef _Map Map;
typedef _Converter Converter;
typedef _GR GR;
typedef typename GR::Edge Item;
static const bool dir = _dir;
private:
const GR& _graph;
Map& _map;
Converter _converter;
public:
GraphArcMapStorage(const GR& graph, Map& map,
const Converter& converter = Converter())
: _graph(graph), _map(map), _converter(converter) {}
virtual ~GraphArcMapStorage() {}
virtual void set(const Item& item ,const std::string& value) {
_map.set(_graph.direct(item, dir), _converter(value));
}
};
class ValueStorageBase {
public:
ValueStorageBase() {}
virtual ~ValueStorageBase() {}
virtual void set(const std::string&) = 0;
};
template <typename _Value, typename _Converter = DefaultConverter<_Value> >
class ValueStorage : public ValueStorageBase {
public:
typedef _Value Value;
typedef _Converter Converter;
private:
Value& _value;
Converter _converter;
public:
ValueStorage(Value& value, const Converter& converter = Converter())
: _value(value), _converter(converter) {}
virtual void set(const std::string& value) {
_value = _converter(value);
}
};
template <typename Value>
struct MapLookUpConverter {
const std::map<std::string, Value>& _map;
MapLookUpConverter(const std::map<std::string, Value>& map)
: _map(map) {}
Value operator()(const std::string& str) {
typename std::map<std::string, Value>::const_iterator it =
_map.find(str);
if (it == _map.end()) {
std::ostringstream msg;
msg << "Item not found: " << str;
throw FormatError(msg.str());
}
return it->second;
}
};
template <typename GR>
struct GraphArcLookUpConverter {
const GR& _graph;
const std::map<std::string, typename GR::Edge>& _map;
GraphArcLookUpConverter(const GR& graph,
const std::map<std::string,
typename GR::Edge>& map)
: _graph(graph), _map(map) {}
typename GR::Arc operator()(const std::string& str) {
if (str.empty() || (str[0] != '+' && str[0] != '-')) {
throw FormatError("Item must start with '+' or '-'");
}
typename std::map<std::string, typename GR::Edge>
::const_iterator it = _map.find(str.substr(1));
if (it == _map.end()) {
throw FormatError("Item not found");
}
return _graph.direct(it->second, str[0] == '+');
}
};
inline bool isWhiteSpace(char c) {
return c == ' ' || c == '\t' || c == '\v' ||
c == '\n' || c == '\r' || c == '\f';
}
inline bool isOct(char c) {
return '0' <= c && c <='7';
}
inline int valueOct(char c) {
LEMON_ASSERT(isOct(c), "The character is not octal.");
return c - '0';
}
inline bool isHex(char c) {
return ('0' <= c && c <= '9') ||
('a' <= c && c <= 'z') ||
('A' <= c && c <= 'Z');
}
inline int valueHex(char c) {
LEMON_ASSERT(isHex(c), "The character is not hexadecimal.");
if ('0' <= c && c <= '9') return c - '0';
if ('a' <= c && c <= 'z') return c - 'a' + 10;
return c - 'A' + 10;
}
inline bool isIdentifierFirstChar(char c) {
return ('a' <= c && c <= 'z') ||
('A' <= c && c <= 'Z') || c == '_';
}
inline bool isIdentifierChar(char c) {
return isIdentifierFirstChar(c) ||
('0' <= c && c <= '9');
}
inline char readEscape(std::istream& is) {
char c;
if (!is.get(c))
throw FormatError("Escape format error");
switch (c) {
case '\\':
return '\\';
case '\"':
return '\"';
case '\'':
return '\'';
case '\?':
return '\?';
case 'a':
return '\a';
case 'b':
return '\b';
case 'f':
return '\f';
case 'n':
return '\n';
case 'r':
return '\r';
case 't':
return '\t';
case 'v':
return '\v';
case 'x':
{
int code;
if (!is.get(c) || !isHex(c))
throw FormatError("Escape format error");
else if (code = valueHex(c), !is.get(c) || !isHex(c)) is.putback(c);
else code = code * 16 + valueHex(c);
return code;
}
default:
{
int code;
if (!isOct(c))
throw FormatError("Escape format error");
else if (code = valueOct(c), !is.get(c) || !isOct(c))
is.putback(c);
else if (code = code * 8 + valueOct(c), !is.get(c) || !isOct(c))
is.putback(c);
else code = code * 8 + valueOct(c);
return code;
}
}
}
inline std::istream& readToken(std::istream& is, std::string& str) {
std::ostringstream os;
char c;
is >> std::ws;
if (!is.get(c))
return is;
if (c == '\"') {
while (is.get(c) && c != '\"') {
if (c == '\\')
c = readEscape(is);
os << c;
}
if (!is)
throw FormatError("Quoted format error");
} else {
is.putback(c);
while (is.get(c) && !isWhiteSpace(c)) {
if (c == '\\')
c = readEscape(is);
os << c;
}
if (!is) {
is.clear();
} else {
is.putback(c);
}
}
str = os.str();
return is;
}
class Section {
public:
virtual ~Section() {}
virtual void process(std::istream& is, int& line_num) = 0;
};
template <typename Functor>
class LineSection : public Section {
private:
Functor _functor;
public:
LineSection(const Functor& functor) : _functor(functor) {}
virtual ~LineSection() {}
virtual void process(std::istream& is, int& line_num) {
char c;
std::string line;
while (is.get(c) && c != '@') {
if (c == '\n') {
++line_num;
} else if (c == '#') {
getline(is, line);
++line_num;
} else if (!isWhiteSpace(c)) {
is.putback(c);
getline(is, line);
_functor(line);
++line_num;
}
}
if (is) is.putback(c);
else if (is.eof()) is.clear();
}
};
template <typename Functor>
class StreamSection : public Section {
private:
Functor _functor;
public:
StreamSection(const Functor& functor) : _functor(functor) {}
virtual ~StreamSection() {}
virtual void process(std::istream& is, int& line_num) {
_functor(is, line_num);
char c;
std::string line;
while (is.get(c) && c != '@') {
if (c == '\n') {
++line_num;
} else if (!isWhiteSpace(c)) {
getline(is, line);
++line_num;
}
}
if (is) is.putback(c);
else if (is.eof()) is.clear();
}
};
}
template <typename DGR>
class DigraphReader;
template <typename TDGR>
DigraphReader<TDGR> digraphReader(TDGR& digraph, std::istream& is = std::cin);
template <typename TDGR>
DigraphReader<TDGR> digraphReader(TDGR& digraph, const std::string& fn);
template <typename TDGR>
DigraphReader<TDGR> digraphReader(TDGR& digraph, const char *fn);
/// \ingroup lemon_io
///
/// \brief \ref lgf-format "LGF" reader for directed graphs
///
/// This utility reads an \ref lgf-format "LGF" file.
///
/// The reading method does a batch processing. The user creates a
/// reader object, then various reading rules can be added to the
/// reader, and eventually the reading is executed with the \c run()
/// member function. A map reading rule can be added to the reader
/// with the \c nodeMap() or \c arcMap() members. An optional
/// converter parameter can also be added as a standard functor
/// converting from \c std::string to the value type of the map. If it
/// is set, it will determine how the tokens in the file should be
/// converted to the value type of the map. If the functor is not set,
/// then a default conversion will be used. One map can be read into
/// multiple map objects at the same time. The \c attribute(), \c
/// node() and \c arc() functions are used to add attribute reading
/// rules.
///
///\code
/// DigraphReader<DGR>(digraph, std::cin).
/// nodeMap("coordinates", coord_map).
/// arcMap("capacity", cap_map).
/// node("source", src).
/// node("target", trg).
/// attribute("caption", caption).
/// run();
///\endcode
///
/// By default, the reader uses the first section in the file of the
/// proper type. If a section has an optional name, then it can be
/// selected for reading by giving an optional name parameter to the
/// \c nodes(), \c arcs() or \c attributes() functions.
///
/// The \c useNodes() and \c useArcs() functions are used to tell the reader
/// that the nodes or arcs should not be constructed (added to the
/// graph) during the reading, but instead the label map of the items
/// are given as a parameter of these functions. An
/// application of these functions is multipass reading, which is
/// important if two \c \@arcs sections must be read from the
/// file. In this case the first phase would read the node set and one
/// of the arc sets, while the second phase would read the second arc
/// set into an \e ArcSet class (\c SmartArcSet or \c ListArcSet).
/// The previously read label node map should be passed to the \c
/// useNodes() functions. Another application of multipass reading when
/// paths are given as a node map or an arc map.
/// It is impossible to read this in
/// a single pass, because the arcs are not constructed when the node
/// maps are read.
template <typename DGR>
class DigraphReader {
public:
typedef DGR Digraph;
private:
TEMPLATE_DIGRAPH_TYPEDEFS(DGR);
std::istream* _is;
bool local_is;
std::string _filename;
DGR& _digraph;
std::string _nodes_caption;
std::string _arcs_caption;
std::string _attributes_caption;
typedef std::map<std::string, Node> NodeIndex;
NodeIndex _node_index;
typedef std::map<std::string, Arc> ArcIndex;
ArcIndex _arc_index;
typedef std::vector<std::pair<std::string,
_reader_bits::MapStorageBase<Node>*> > NodeMaps;
NodeMaps _node_maps;
typedef std::vector<std::pair<std::string,
_reader_bits::MapStorageBase<Arc>*> >ArcMaps;
ArcMaps _arc_maps;
typedef std::multimap<std::string, _reader_bits::ValueStorageBase*>
Attributes;
Attributes _attributes;
bool _use_nodes;
bool _use_arcs;
bool _skip_nodes;
bool _skip_arcs;
int line_num;
std::istringstream line;
public:
/// \brief Constructor
///
/// Construct a directed graph reader, which reads from the given
/// input stream.
DigraphReader(DGR& digraph, std::istream& is = std::cin)
: _is(&is), local_is(false), _digraph(digraph),
_use_nodes(false), _use_arcs(false),
_skip_nodes(false), _skip_arcs(false) {}
/// \brief Constructor
///
/// Construct a directed graph reader, which reads from the given
/// file.
DigraphReader(DGR& digraph, const std::string& fn)
: _is(new std::ifstream(fn.c_str())), local_is(true),
_filename(fn), _digraph(digraph),
_use_nodes(false), _use_arcs(false),
_skip_nodes(false), _skip_arcs(false) {
if (!(*_is)) {
delete _is;
throw IoError("Cannot open file", fn);
}
}
/// \brief Constructor
///
/// Construct a directed graph reader, which reads from the given
/// file.
DigraphReader(DGR& digraph, const char* fn)
: _is(new std::ifstream(fn)), local_is(true),
_filename(fn), _digraph(digraph),
_use_nodes(false), _use_arcs(false),
_skip_nodes(false), _skip_arcs(false) {
if (!(*_is)) {
delete _is;
throw IoError("Cannot open file", fn);
}
}
/// \brief Destructor
~DigraphReader() {
for (typename NodeMaps::iterator it = _node_maps.begin();
it != _node_maps.end(); ++it) {
delete it->second;
}
for (typename ArcMaps::iterator it = _arc_maps.begin();
it != _arc_maps.end(); ++it) {
delete it->second;
}
for (typename Attributes::iterator it = _attributes.begin();
it != _attributes.end(); ++it) {
delete it->second;
}
if (local_is) {
delete _is;
}
}
private:
template <typename TDGR>
friend DigraphReader<TDGR> digraphReader(TDGR& digraph, std::istream& is);
template <typename TDGR>
friend DigraphReader<TDGR> digraphReader(TDGR& digraph,
const std::string& fn);
template <typename TDGR>
friend DigraphReader<TDGR> digraphReader(TDGR& digraph, const char *fn);
DigraphReader(DigraphReader& other)
: _is(other._is), local_is(other.local_is), _digraph(other._digraph),
_use_nodes(other._use_nodes), _use_arcs(other._use_arcs),
_skip_nodes(other._skip_nodes), _skip_arcs(other._skip_arcs) {
other._is = 0;
other.local_is = false;
_node_index.swap(other._node_index);
_arc_index.swap(other._arc_index);
_node_maps.swap(other._node_maps);
_arc_maps.swap(other._arc_maps);
_attributes.swap(other._attributes);
_nodes_caption = other._nodes_caption;
_arcs_caption = other._arcs_caption;
_attributes_caption = other._attributes_caption;
}
DigraphReader& operator=(const DigraphReader&);
public:
/// \name Reading Rules
/// @{
/// \brief Node map reading rule
///
/// Add a node map reading rule to the reader.
template <typename Map>
DigraphReader& nodeMap(const std::string& caption, Map& map) {
checkConcept<concepts::WriteMap<Node, typename Map::Value>, Map>();
_reader_bits::MapStorageBase<Node>* storage =
new _reader_bits::MapStorage<Node, Map>(map);
_node_maps.push_back(std::make_pair(caption, storage));
return *this;
}
/// \brief Node map reading rule
///
/// Add a node map reading rule with specialized converter to the
/// reader.
template <typename Map, typename Converter>
DigraphReader& nodeMap(const std::string& caption, Map& map,
const Converter& converter = Converter()) {
checkConcept<concepts::WriteMap<Node, typename Map::Value>, Map>();
_reader_bits::MapStorageBase<Node>* storage =
new _reader_bits::MapStorage<Node, Map, Converter>(map, converter);
_node_maps.push_back(std::make_pair(caption, storage));
return *this;
}
/// \brief Arc map reading rule
///
/// Add an arc map reading rule to the reader.
template <typename Map>
DigraphReader& arcMap(const std::string& caption, Map& map) {
checkConcept<concepts::WriteMap<Arc, typename Map::Value>, Map>();
_reader_bits::MapStorageBase<Arc>* storage =
new _reader_bits::MapStorage<Arc, Map>(map);
_arc_maps.push_back(std::make_pair(caption, storage));
return *this;
}
/// \brief Arc map reading rule
///
/// Add an arc map reading rule with specialized converter to the
/// reader.
template <typename Map, typename Converter>
DigraphReader& arcMap(const std::string& caption, Map& map,
const Converter& converter = Converter()) {
checkConcept<concepts::WriteMap<Arc, typename Map::Value>, Map>();
_reader_bits::MapStorageBase<Arc>* storage =
new _reader_bits::MapStorage<Arc, Map, Converter>(map, converter);
_arc_maps.push_back(std::make_pair(caption, storage));
return *this;
}
/// \brief Attribute reading rule
///
/// Add an attribute reading rule to the reader.
template <typename Value>
DigraphReader& attribute(const std::string& caption, Value& value) {
_reader_bits::ValueStorageBase* storage =
new _reader_bits::ValueStorage<Value>(value);
_attributes.insert(std::make_pair(caption, storage));
return *this;
}
/// \brief Attribute reading rule
///
/// Add an attribute reading rule with specialized converter to the
/// reader.
template <typename Value, typename Converter>
DigraphReader& attribute(const std::string& caption, Value& value,
const Converter& converter = Converter()) {
_reader_bits::ValueStorageBase* storage =
new _reader_bits::ValueStorage<Value, Converter>(value, converter);
_attributes.insert(std::make_pair(caption, storage));
return *this;
}
/// \brief Node reading rule
///
/// Add a node reading rule to reader.
DigraphReader& node(const std::string& caption, Node& node) {
typedef _reader_bits::MapLookUpConverter<Node> Converter;
Converter converter(_node_index);
_reader_bits::ValueStorageBase* storage =
new _reader_bits::ValueStorage<Node, Converter>(node, converter);
_attributes.insert(std::make_pair(caption, storage));
return *this;
}
/// \brief Arc reading rule
///
/// Add an arc reading rule to reader.
DigraphReader& arc(const std::string& caption, Arc& arc) {
typedef _reader_bits::MapLookUpConverter<Arc> Converter;
Converter converter(_arc_index);
_reader_bits::ValueStorageBase* storage =
new _reader_bits::ValueStorage<Arc, Converter>(arc, converter);
_attributes.insert(std::make_pair(caption, storage));
return *this;
}
/// @}
/// \name Select Section by Name
/// @{
/// \brief Set \c \@nodes section to be read
///
/// Set \c \@nodes section to be read
DigraphReader& nodes(const std::string& caption) {
_nodes_caption = caption;
return *this;
}
/// \brief Set \c \@arcs section to be read
///
/// Set \c \@arcs section to be read
DigraphReader& arcs(const std::string& caption) {
_arcs_caption = caption;
return *this;
}
/// \brief Set \c \@attributes section to be read
///
/// Set \c \@attributes section to be read
DigraphReader& attributes(const std::string& caption) {
_attributes_caption = caption;
return *this;
}
/// @}
/// \name Using Previously Constructed Node or Arc Set
/// @{
/// \brief Use previously constructed node set
///
/// Use previously constructed node set, and specify the node
/// label map.
template <typename Map>
DigraphReader& useNodes(const Map& map) {
checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>();
LEMON_ASSERT(!_use_nodes, "Multiple usage of useNodes() member");
_use_nodes = true;
_writer_bits::DefaultConverter<typename Map::Value> converter;
for (NodeIt n(_digraph); n != INVALID; ++n) {
_node_index.insert(std::make_pair(converter(map[n]), n));
}
return *this;
}
/// \brief Use previously constructed node set
///
/// Use previously constructed node set, and specify the node
/// label map and a functor which converts the label map values to
/// \c std::string.
template <typename Map, typename Converter>
DigraphReader& useNodes(const Map& map,
const Converter& converter = Converter()) {
checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>();
LEMON_ASSERT(!_use_nodes, "Multiple usage of useNodes() member");
_use_nodes = true;
for (NodeIt n(_digraph); n != INVALID; ++n) {
_node_index.insert(std::make_pair(converter(map[n]), n));
}
return *this;
}
/// \brief Use previously constructed arc set
///
/// Use previously constructed arc set, and specify the arc
/// label map.
template <typename Map>
DigraphReader& useArcs(const Map& map) {
checkConcept<concepts::ReadMap<Arc, typename Map::Value>, Map>();
LEMON_ASSERT(!_use_arcs, "Multiple usage of useArcs() member");
_use_arcs = true;
_writer_bits::DefaultConverter<typename Map::Value> converter;
for (ArcIt a(_digraph); a != INVALID; ++a) {
_arc_index.insert(std::make_pair(converter(map[a]), a));
}
return *this;
}
/// \brief Use previously constructed arc set
///
/// Use previously constructed arc set, and specify the arc
/// label map and a functor which converts the label map values to
/// \c std::string.
template <typename Map, typename Converter>
DigraphReader& useArcs(const Map& map,
const Converter& converter = Converter()) {
checkConcept<concepts::ReadMap<Arc, typename Map::Value>, Map>();
LEMON_ASSERT(!_use_arcs, "Multiple usage of useArcs() member");
_use_arcs = true;
for (ArcIt a(_digraph); a != INVALID; ++a) {
_arc_index.insert(std::make_pair(converter(map[a]), a));
}
return *this;
}
/// \brief Skips the reading of node section
///
/// Omit the reading of the node section. This implies that each node
/// map reading rule will be abandoned, and the nodes of the graph
/// will not be constructed, which usually cause that the arc set
/// could not be read due to lack of node name resolving.
/// Therefore \c skipArcs() function should also be used, or
/// \c useNodes() should be used to specify the label of the nodes.
DigraphReader& skipNodes() {
LEMON_ASSERT(!_skip_nodes, "Skip nodes already set");
_skip_nodes = true;
return *this;
}
/// \brief Skips the reading of arc section
///
/// Omit the reading of the arc section. This implies that each arc
/// map reading rule will be abandoned, and the arcs of the graph
/// will not be constructed.
DigraphReader& skipArcs() {
LEMON_ASSERT(!_skip_arcs, "Skip arcs already set");
_skip_arcs = true;
return *this;
}
/// @}
private:
bool readLine() {
std::string str;
while(++line_num, std::getline(*_is, str)) {
line.clear(); line.str(str);
char c;
if (line >> std::ws >> c && c != '#') {
line.putback(c);
return true;
}
}
return false;
}
bool readSuccess() {
return static_cast<bool>(*_is);
}
void skipSection() {
char c;
while (readSuccess() && line >> c && c != '@') {
readLine();
}
if (readSuccess()) {
line.putback(c);
}
}
void readNodes() {
std::vector<int> map_index(_node_maps.size());
int map_num, label_index;
char c;
if (!readLine() || !(line >> c) || c == '@') {
if (readSuccess() && line) line.putback(c);
if (!_node_maps.empty())
throw FormatError("Cannot find map names");
return;
}
line.putback(c);
{
std::map<std::string, int> maps;
std::string map;
int index = 0;
while (_reader_bits::readToken(line, map)) {
if (maps.find(map) != maps.end()) {
std::ostringstream msg;
msg << "Multiple occurence of node map: " << map;
throw FormatError(msg.str());
}
maps.insert(std::make_pair(map, index));
++index;
}
for (int i = 0; i < static_cast<int>(_node_maps.size()); ++i) {
std::map<std::string, int>::iterator jt =
maps.find(_node_maps[i].first);
if (jt == maps.end()) {
std::ostringstream msg;
msg << "Map not found: " << _node_maps[i].first;
throw FormatError(msg.str());
}
map_index[i] = jt->second;
}
{
std::map<std::string, int>::iterator jt = maps.find("label");
if (jt != maps.end()) {
label_index = jt->second;
} else {
label_index = -1;
}
}
map_num = maps.size();
}
while (readLine() && line >> c && c != '@') {
line.putback(c);
std::vector<std::string> tokens(map_num);
for (int i = 0; i < map_num; ++i) {
if (!_reader_bits::readToken(line, tokens[i])) {
std::ostringstream msg;
msg << "Column not found (" << i + 1 << ")";
throw FormatError(msg.str());
}
}
if (line >> std::ws >> c)
throw FormatError("Extra character at the end of line");
Node n;
if (!_use_nodes) {
n = _digraph.addNode();
if (label_index != -1)
_node_index.insert(std::make_pair(tokens[label_index], n));
} else {
if (label_index == -1)
throw FormatError("Label map not found");
typename std::map<std::string, Node>::iterator it =
_node_index.find(tokens[label_index]);
if (it == _node_index.end()) {
std::ostringstream msg;
msg << "Node with label not found: " << tokens[label_index];
throw FormatError(msg.str());
}
n = it->second;
}
for (int i = 0; i < static_cast<int>(_node_maps.size()); ++i) {
_node_maps[i].second->set(n, tokens[map_index[i]]);
}
}
if (readSuccess()) {
line.putback(c);
}
}
void readArcs() {
std::vector<int> map_index(_arc_maps.size());
int map_num, label_index;
char c;
if (!readLine() || !(line >> c) || c == '@') {
if (readSuccess() && line) line.putback(c);
if (!_arc_maps.empty())
throw FormatError("Cannot find map names");
return;
}
line.putback(c);
{
std::map<std::string, int> maps;
std::string map;
int index = 0;
while (_reader_bits::readToken(line, map)) {
if (maps.find(map) != maps.end()) {
std::ostringstream msg;
msg << "Multiple occurence of arc map: " << map;
throw FormatError(msg.str());
}
maps.insert(std::make_pair(map, index));
++index;
}
for (int i = 0; i < static_cast<int>(_arc_maps.size()); ++i) {
std::map<std::string, int>::iterator jt =
maps.find(_arc_maps[i].first);
if (jt == maps.end()) {
std::ostringstream msg;
msg << "Map not found: " << _arc_maps[i].first;
throw FormatError(msg.str());
}
map_index[i] = jt->second;
}
{
std::map<std::string, int>::iterator jt = maps.find("label");
if (jt != maps.end()) {
label_index = jt->second;
} else {
label_index = -1;
}
}
map_num = maps.size();
}
while (readLine() && line >> c && c != '@') {
line.putback(c);
std::string source_token;
std::string target_token;
if (!_reader_bits::readToken(line, source_token))
throw FormatError("Source not found");
if (!_reader_bits::readToken(line, target_token))
throw FormatError("Target not found");
std::vector<std::string> tokens(map_num);
for (int i = 0; i < map_num; ++i) {
if (!_reader_bits::readToken(line, tokens[i])) {
std::ostringstream msg;
msg << "Column not found (" << i + 1 << ")";
throw FormatError(msg.str());
}
}
if (line >> std::ws >> c)
throw FormatError("Extra character at the end of line");
Arc a;
if (!_use_arcs) {
typename NodeIndex::iterator it;
it = _node_index.find(source_token);
if (it == _node_index.end()) {
std::ostringstream msg;
msg << "Item not found: " << source_token;
throw FormatError(msg.str());
}
Node source = it->second;
it = _node_index.find(target_token);
if (it == _node_index.end()) {
std::ostringstream msg;
msg << "Item not found: " << target_token;
throw FormatError(msg.str());
}
Node target = it->second;
a = _digraph.addArc(source, target);
if (label_index != -1)
_arc_index.insert(std::make_pair(tokens[label_index], a));
} else {
if (label_index == -1)
throw FormatError("Label map not found");
typename std::map<std::string, Arc>::iterator it =
_arc_index.find(tokens[label_index]);
if (it == _arc_index.end()) {
std::ostringstream msg;
msg << "Arc with label not found: " << tokens[label_index];
throw FormatError(msg.str());
}
a = it->second;
}
for (int i = 0; i < static_cast<int>(_arc_maps.size()); ++i) {
_arc_maps[i].second->set(a, tokens[map_index[i]]);
}
}
if (readSuccess()) {
line.putback(c);
}
}
void readAttributes() {
std::set<std::string> read_attr;
char c;
while (readLine() && line >> c && c != '@') {
line.putback(c);
std::string attr, token;
if (!_reader_bits::readToken(line, attr))
throw FormatError("Attribute name not found");
if (!_reader_bits::readToken(line, token))
throw FormatError("Attribute value not found");
if (line >> c)
throw FormatError("Extra character at the end of line");
{
std::set<std::string>::iterator it = read_attr.find(attr);
if (it != read_attr.end()) {
std::ostringstream msg;
msg << "Multiple occurence of attribute: " << attr;
throw FormatError(msg.str());
}
read_attr.insert(attr);
}
{
typename Attributes::iterator it = _attributes.lower_bound(attr);
while (it != _attributes.end() && it->first == attr) {
it->second->set(token);
++it;
}
}
}
if (readSuccess()) {
line.putback(c);
}
for (typename Attributes::iterator it = _attributes.begin();
it != _attributes.end(); ++it) {
if (read_attr.find(it->first) == read_attr.end()) {
std::ostringstream msg;
msg << "Attribute not found: " << it->first;
throw FormatError(msg.str());
}
}
}
public:
/// \name Execution of the Reader
/// @{
/// \brief Start the batch processing
///
/// This function starts the batch processing
void run() {
LEMON_ASSERT(_is != 0, "This reader assigned to an other reader");
bool nodes_done = _skip_nodes;
bool arcs_done = _skip_arcs;
bool attributes_done = false;
line_num = 0;
readLine();
skipSection();
while (readSuccess()) {
try {
char c;
std::string section, caption;
line >> c;
_reader_bits::readToken(line, section);
_reader_bits::readToken(line, caption);
if (line >> c)
throw FormatError("Extra character at the end of line");
if (section == "nodes" && !nodes_done) {
if (_nodes_caption.empty() || _nodes_caption == caption) {
readNodes();
nodes_done = true;
}
} else if ((section == "arcs" || section == "edges") &&
!arcs_done) {
if (_arcs_caption.empty() || _arcs_caption == caption) {
readArcs();
arcs_done = true;
}
} else if (section == "attributes" && !attributes_done) {
if (_attributes_caption.empty() || _attributes_caption == caption) {
readAttributes();
attributes_done = true;
}
} else {
readLine();
skipSection();
}
} catch (FormatError& error) {
error.line(line_num);
error.file(_filename);
throw;
}
}
if (!nodes_done) {
throw FormatError("Section @nodes not found");
}
if (!arcs_done) {
throw FormatError("Section @arcs not found");
}
if (!attributes_done && !_attributes.empty()) {
throw FormatError("Section @attributes not found");
}
}
/// @}
};
/// \ingroup lemon_io
///
/// \brief Return a \ref DigraphReader class
///
/// This function just returns a \ref DigraphReader class.
///
/// With this function a digraph can be read from an
/// \ref lgf-format "LGF" file or input stream with several maps and
/// attributes. For example, there is network flow problem on a
/// digraph, i.e. a digraph with a \e capacity map on the arcs and
/// \e source and \e target nodes. This digraph can be read with the
/// following code:
///
///\code
///ListDigraph digraph;
///ListDigraph::ArcMap<int> cm(digraph);
///ListDigraph::Node src, trg;
///digraphReader(digraph, std::cin).
/// arcMap("capacity", cap).
/// node("source", src).
/// node("target", trg).
/// run();
///\endcode
///
/// For a complete documentation, please see the \ref DigraphReader
/// class documentation.
/// \warning Don't forget to put the \ref DigraphReader::run() "run()"
/// to the end of the parameter list.
/// \relates DigraphReader
/// \sa digraphReader(TDGR& digraph, const std::string& fn)
/// \sa digraphReader(TDGR& digraph, const char* fn)
template <typename TDGR>
DigraphReader<TDGR> digraphReader(TDGR& digraph, std::istream& is) {
DigraphReader<TDGR> tmp(digraph, is);
return tmp;
}
/// \brief Return a \ref DigraphReader class
///
/// This function just returns a \ref DigraphReader class.
/// \relates DigraphReader
/// \sa digraphReader(TDGR& digraph, std::istream& is)
template <typename TDGR>
DigraphReader<TDGR> digraphReader(TDGR& digraph, const std::string& fn) {
DigraphReader<TDGR> tmp(digraph, fn);
return tmp;
}
/// \brief Return a \ref DigraphReader class
///
/// This function just returns a \ref DigraphReader class.
/// \relates DigraphReader
/// \sa digraphReader(TDGR& digraph, std::istream& is)
template <typename TDGR>
DigraphReader<TDGR> digraphReader(TDGR& digraph, const char* fn) {
DigraphReader<TDGR> tmp(digraph, fn);
return tmp;
}
template <typename GR>
class GraphReader;
template <typename TGR>
GraphReader<TGR> graphReader(TGR& graph, std::istream& is = std::cin);
template <typename TGR>
GraphReader<TGR> graphReader(TGR& graph, const std::string& fn);
template <typename TGR>
GraphReader<TGR> graphReader(TGR& graph, const char *fn);
/// \ingroup lemon_io
///
/// \brief \ref lgf-format "LGF" reader for undirected graphs
///
/// This utility reads an \ref lgf-format "LGF" file.
///
/// It can be used almost the same way as \c DigraphReader.
/// The only difference is that this class can handle edges and
/// edge maps as well as arcs and arc maps.
///
/// The columns in the \c \@edges (or \c \@arcs) section are the
/// edge maps. However, if there are two maps with the same name
/// prefixed with \c '+' and \c '-', then these can be read into an
/// arc map. Similarly, an attribute can be read into an arc, if
/// it's value is an edge label prefixed with \c '+' or \c '-'.
template <typename GR>
class GraphReader {
public:
typedef GR Graph;
private:
TEMPLATE_GRAPH_TYPEDEFS(GR);
std::istream* _is;
bool local_is;
std::string _filename;
GR& _graph;
std::string _nodes_caption;
std::string _edges_caption;
std::string _attributes_caption;
typedef std::map<std::string, Node> NodeIndex;
NodeIndex _node_index;
typedef std::map<std::string, Edge> EdgeIndex;
EdgeIndex _edge_index;
typedef std::vector<std::pair<std::string,
_reader_bits::MapStorageBase<Node>*> > NodeMaps;
NodeMaps _node_maps;
typedef std::vector<std::pair<std::string,
_reader_bits::MapStorageBase<Edge>*> > EdgeMaps;
EdgeMaps _edge_maps;
typedef std::multimap<std::string, _reader_bits::ValueStorageBase*>
Attributes;
Attributes _attributes;
bool _use_nodes;
bool _use_edges;
bool _skip_nodes;
bool _skip_edges;
int line_num;
std::istringstream line;
public:
/// \brief Constructor
///
/// Construct an undirected graph reader, which reads from the given
/// input stream.
GraphReader(GR& graph, std::istream& is = std::cin)
: _is(&is), local_is(false), _graph(graph),
_use_nodes(false), _use_edges(false),
_skip_nodes(false), _skip_edges(false) {}
/// \brief Constructor
///
/// Construct an undirected graph reader, which reads from the given
/// file.
GraphReader(GR& graph, const std::string& fn)
: _is(new std::ifstream(fn.c_str())), local_is(true),
_filename(fn), _graph(graph),
_use_nodes(false), _use_edges(false),
_skip_nodes(false), _skip_edges(false) {
if (!(*_is)) {
delete _is;
throw IoError("Cannot open file", fn);
}
}
/// \brief Constructor
///
/// Construct an undirected graph reader, which reads from the given
/// file.
GraphReader(GR& graph, const char* fn)
: _is(new std::ifstream(fn)), local_is(true),
_filename(fn), _graph(graph),
_use_nodes(false), _use_edges(false),
_skip_nodes(false), _skip_edges(false) {
if (!(*_is)) {
delete _is;
throw IoError("Cannot open file", fn);
}
}
/// \brief Destructor
~GraphReader() {
for (typename NodeMaps::iterator it = _node_maps.begin();
it != _node_maps.end(); ++it) {
delete it->second;
}
for (typename EdgeMaps::iterator it = _edge_maps.begin();
it != _edge_maps.end(); ++it) {
delete it->second;
}
for (typename Attributes::iterator it = _attributes.begin();
it != _attributes.end(); ++it) {
delete it->second;
}
if (local_is) {
delete _is;
}
}
private:
template <typename TGR>
friend GraphReader<TGR> graphReader(TGR& graph, std::istream& is);
template <typename TGR>
friend GraphReader<TGR> graphReader(TGR& graph, const std::string& fn);
template <typename TGR>
friend GraphReader<TGR> graphReader(TGR& graph, const char *fn);
GraphReader(GraphReader& other)
: _is(other._is), local_is(other.local_is), _graph(other._graph),
_use_nodes(other._use_nodes), _use_edges(other._use_edges),
_skip_nodes(other._skip_nodes), _skip_edges(other._skip_edges) {
other._is = 0;
other.local_is = false;
_node_index.swap(other._node_index);
_edge_index.swap(other._edge_index);
_node_maps.swap(other._node_maps);
_edge_maps.swap(other._edge_maps);
_attributes.swap(other._attributes);
_nodes_caption = other._nodes_caption;
_edges_caption = other._edges_caption;
_attributes_caption = other._attributes_caption;
}
GraphReader& operator=(const GraphReader&);
public:
/// \name Reading Rules
/// @{
/// \brief Node map reading rule
///
/// Add a node map reading rule to the reader.
template <typename Map>
GraphReader& nodeMap(const std::string& caption, Map& map) {
checkConcept<concepts::WriteMap<Node, typename Map::Value>, Map>();
_reader_bits::MapStorageBase<Node>* storage =
new _reader_bits::MapStorage<Node, Map>(map);
_node_maps.push_back(std::make_pair(caption, storage));
return *this;
}
/// \brief Node map reading rule
///
/// Add a node map reading rule with specialized converter to the
/// reader.
template <typename Map, typename Converter>
GraphReader& nodeMap(const std::string& caption, Map& map,
const Converter& converter = Converter()) {
checkConcept<concepts::WriteMap<Node, typename Map::Value>, Map>();
_reader_bits::MapStorageBase<Node>* storage =
new _reader_bits::MapStorage<Node, Map, Converter>(map, converter);
_node_maps.push_back(std::make_pair(caption, storage));
return *this;
}
/// \brief Edge map reading rule
///
/// Add an edge map reading rule to the reader.
template <typename Map>
GraphReader& edgeMap(const std::string& caption, Map& map) {
checkConcept<concepts::WriteMap<Edge, typename Map::Value>, Map>();
_reader_bits::MapStorageBase<Edge>* storage =
new _reader_bits::MapStorage<Edge, Map>(map);
_edge_maps.push_back(std::make_pair(caption, storage));
return *this;
}
/// \brief Edge map reading rule
///
/// Add an edge map reading rule with specialized converter to the
/// reader.
template <typename Map, typename Converter>
GraphReader& edgeMap(const std::string& caption, Map& map,
const Converter& converter = Converter()) {
checkConcept<concepts::WriteMap<Edge, typename Map::Value>, Map>();
_reader_bits::MapStorageBase<Edge>* storage =
new _reader_bits::MapStorage<Edge, Map, Converter>(map, converter);
_edge_maps.push_back(std::make_pair(caption, storage));
return *this;
}
/// \brief Arc map reading rule
///
/// Add an arc map reading rule to the reader.
template <typename Map>
GraphReader& arcMap(const std::string& caption, Map& map) {
checkConcept<concepts::WriteMap<Arc, typename Map::Value>, Map>();
_reader_bits::MapStorageBase<Edge>* forward_storage =
new _reader_bits::GraphArcMapStorage<Graph, true, Map>(_graph, map);
_edge_maps.push_back(std::make_pair('+' + caption, forward_storage));
_reader_bits::MapStorageBase<Edge>* backward_storage =
new _reader_bits::GraphArcMapStorage<GR, false, Map>(_graph, map);
_edge_maps.push_back(std::make_pair('-' + caption, backward_storage));
return *this;
}
/// \brief Arc map reading rule
///
/// Add an arc map reading rule with specialized converter to the
/// reader.
template <typename Map, typename Converter>
GraphReader& arcMap(const std::string& caption, Map& map,
const Converter& converter = Converter()) {
checkConcept<concepts::WriteMap<Arc, typename Map::Value>, Map>();
_reader_bits::MapStorageBase<Edge>* forward_storage =
new _reader_bits::GraphArcMapStorage<GR, true, Map, Converter>
(_graph, map, converter);
_edge_maps.push_back(std::make_pair('+' + caption, forward_storage));
_reader_bits::MapStorageBase<Edge>* backward_storage =
new _reader_bits::GraphArcMapStorage<GR, false, Map, Converter>
(_graph, map, converter);
_edge_maps.push_back(std::make_pair('-' + caption, backward_storage));
return *this;
}
/// \brief Attribute reading rule
///
/// Add an attribute reading rule to the reader.
template <typename Value>
GraphReader& attribute(const std::string& caption, Value& value) {
_reader_bits::ValueStorageBase* storage =
new _reader_bits::ValueStorage<Value>(value);
_attributes.insert(std::make_pair(caption, storage));
return *this;
}
/// \brief Attribute reading rule
///
/// Add an attribute reading rule with specialized converter to the
/// reader.
template <typename Value, typename Converter>
GraphReader& attribute(const std::string& caption, Value& value,
const Converter& converter = Converter()) {
_reader_bits::ValueStorageBase* storage =
new _reader_bits::ValueStorage<Value, Converter>(value, converter);
_attributes.insert(std::make_pair(caption, storage));
return *this;
}
/// \brief Node reading rule
///
/// Add a node reading rule to reader.
GraphReader& node(const std::string& caption, Node& node) {
typedef _reader_bits::MapLookUpConverter<Node> Converter;
Converter converter(_node_index);
_reader_bits::ValueStorageBase* storage =
new _reader_bits::ValueStorage<Node, Converter>(node, converter);
_attributes.insert(std::make_pair(caption, storage));
return *this;
}
/// \brief Edge reading rule
///
/// Add an edge reading rule to reader.
GraphReader& edge(const std::string& caption, Edge& edge) {
typedef _reader_bits::MapLookUpConverter<Edge> Converter;
Converter converter(_edge_index);
_reader_bits::ValueStorageBase* storage =
new _reader_bits::ValueStorage<Edge, Converter>(edge, converter);
_attributes.insert(std::make_pair(caption, storage));
return *this;
}
/// \brief Arc reading rule
///
/// Add an arc reading rule to reader.
GraphReader& arc(const std::string& caption, Arc& arc) {
typedef _reader_bits::GraphArcLookUpConverter<GR> Converter;
Converter converter(_graph, _edge_index);
_reader_bits::ValueStorageBase* storage =
new _reader_bits::ValueStorage<Arc, Converter>(arc, converter);
_attributes.insert(std::make_pair(caption, storage));
return *this;
}
/// @}
/// \name Select Section by Name
/// @{
/// \brief Set \c \@nodes section to be read
///
/// Set \c \@nodes section to be read.
GraphReader& nodes(const std::string& caption) {
_nodes_caption = caption;
return *this;
}
/// \brief Set \c \@edges section to be read
///
/// Set \c \@edges section to be read.
GraphReader& edges(const std::string& caption) {
_edges_caption = caption;
return *this;
}
/// \brief Set \c \@attributes section to be read
///
/// Set \c \@attributes section to be read.
GraphReader& attributes(const std::string& caption) {
_attributes_caption = caption;
return *this;
}
/// @}
/// \name Using Previously Constructed Node or Edge Set
/// @{
/// \brief Use previously constructed node set
///
/// Use previously constructed node set, and specify the node
/// label map.
template <typename Map>
GraphReader& useNodes(const Map& map) {
checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>();
LEMON_ASSERT(!_use_nodes, "Multiple usage of useNodes() member");
_use_nodes = true;
_writer_bits::DefaultConverter<typename Map::Value> converter;
for (NodeIt n(_graph); n != INVALID; ++n) {
_node_index.insert(std::make_pair(converter(map[n]), n));
}
return *this;
}
/// \brief Use previously constructed node set
///
/// Use previously constructed node set, and specify the node
/// label map and a functor which converts the label map values to
/// \c std::string.
template <typename Map, typename Converter>
GraphReader& useNodes(const Map& map,
const Converter& converter = Converter()) {
checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>();
LEMON_ASSERT(!_use_nodes, "Multiple usage of useNodes() member");
_use_nodes = true;
for (NodeIt n(_graph); n != INVALID; ++n) {
_node_index.insert(std::make_pair(converter(map[n]), n));
}
return *this;
}
/// \brief Use previously constructed edge set
///
/// Use previously constructed edge set, and specify the edge
/// label map.
template <typename Map>
GraphReader& useEdges(const Map& map) {
checkConcept<concepts::ReadMap<Edge, typename Map::Value>, Map>();
LEMON_ASSERT(!_use_edges, "Multiple usage of useEdges() member");
_use_edges = true;
_writer_bits::DefaultConverter<typename Map::Value> converter;
for (EdgeIt a(_graph); a != INVALID; ++a) {
_edge_index.insert(std::make_pair(converter(map[a]), a));
}
return *this;
}
/// \brief Use previously constructed edge set
///
/// Use previously constructed edge set, and specify the edge
/// label map and a functor which converts the label map values to
/// \c std::string.
template <typename Map, typename Converter>
GraphReader& useEdges(const Map& map,
const Converter& converter = Converter()) {
checkConcept<concepts::ReadMap<Edge, typename Map::Value>, Map>();
LEMON_ASSERT(!_use_edges, "Multiple usage of useEdges() member");
_use_edges = true;
for (EdgeIt a(_graph); a != INVALID; ++a) {
_edge_index.insert(std::make_pair(converter(map[a]), a));
}
return *this;
}
/// \brief Skip the reading of node section
///
/// Omit the reading of the node section. This implies that each node
/// map reading rule will be abandoned, and the nodes of the graph
/// will not be constructed, which usually cause that the edge set
/// could not be read due to lack of node name
/// could not be read due to lack of node name resolving.
/// Therefore \c skipEdges() function should also be used, or
/// \c useNodes() should be used to specify the label of the nodes.
GraphReader& skipNodes() {
LEMON_ASSERT(!_skip_nodes, "Skip nodes already set");
_skip_nodes = true;
return *this;
}
/// \brief Skip the reading of edge section
///
/// Omit the reading of the edge section. This implies that each edge
/// map reading rule will be abandoned, and the edges of the graph
/// will not be constructed.
GraphReader& skipEdges() {
LEMON_ASSERT(!_skip_edges, "Skip edges already set");
_skip_edges = true;
return *this;
}
/// @}
private:
bool readLine() {
std::string str;
while(++line_num, std::getline(*_is, str)) {
line.clear(); line.str(str);
char c;
if (line >> std::ws >> c && c != '#') {
line.putback(c);
return true;
}
}
return false;
}
bool readSuccess() {
return static_cast<bool>(*_is);
}
void skipSection() {
char c;
while (readSuccess() && line >> c && c != '@') {
readLine();
}
if (readSuccess()) {
line.putback(c);
}
}
void readNodes() {
std::vector<int> map_index(_node_maps.size());
int map_num, label_index;
char c;
if (!readLine() || !(line >> c) || c == '@') {
if (readSuccess() && line) line.putback(c);
if (!_node_maps.empty())
throw FormatError("Cannot find map names");
return;
}
line.putback(c);
{
std::map<std::string, int> maps;
std::string map;
int index = 0;
while (_reader_bits::readToken(line, map)) {
if (maps.find(map) != maps.end()) {
std::ostringstream msg;
msg << "Multiple occurence of node map: " << map;
throw FormatError(msg.str());
}
maps.insert(std::make_pair(map, index));
++index;
}
for (int i = 0; i < static_cast<int>(_node_maps.size()); ++i) {
std::map<std::string, int>::iterator jt =
maps.find(_node_maps[i].first);
if (jt == maps.end()) {
std::ostringstream msg;
msg << "Map not found: " << _node_maps[i].first;
throw FormatError(msg.str());
}
map_index[i] = jt->second;
}
{
std::map<std::string, int>::iterator jt = maps.find("label");
if (jt != maps.end()) {
label_index = jt->second;
} else {
label_index = -1;
}
}
map_num = maps.size();
}
while (readLine() && line >> c && c != '@') {
line.putback(c);
std::vector<std::string> tokens(map_num);
for (int i = 0; i < map_num; ++i) {
if (!_reader_bits::readToken(line, tokens[i])) {
std::ostringstream msg;
msg << "Column not found (" << i + 1 << ")";
throw FormatError(msg.str());
}
}
if (line >> std::ws >> c)
throw FormatError("Extra character at the end of line");
Node n;
if (!_use_nodes) {
n = _graph.addNode();
if (label_index != -1)
_node_index.insert(std::make_pair(tokens[label_index], n));
} else {
if (label_index == -1)
throw FormatError("Label map not found");
typename std::map<std::string, Node>::iterator it =
_node_index.find(tokens[label_index]);
if (it == _node_index.end()) {
std::ostringstream msg;
msg << "Node with label not found: " << tokens[label_index];
throw FormatError(msg.str());
}
n = it->second;
}
for (int i = 0; i < static_cast<int>(_node_maps.size()); ++i) {
_node_maps[i].second->set(n, tokens[map_index[i]]);
}
}
if (readSuccess()) {
line.putback(c);
}
}
void readEdges() {
std::vector<int> map_index(_edge_maps.size());
int map_num, label_index;
char c;
if (!readLine() || !(line >> c) || c == '@') {
if (readSuccess() && line) line.putback(c);
if (!_edge_maps.empty())
throw FormatError("Cannot find map names");
return;
}
line.putback(c);
{
std::map<std::string, int> maps;
std::string map;
int index = 0;
while (_reader_bits::readToken(line, map)) {
if (maps.find(map) != maps.end()) {
std::ostringstream msg;
msg << "Multiple occurence of edge map: " << map;
throw FormatError(msg.str());
}
maps.insert(std::make_pair(map, index));
++index;
}
for (int i = 0; i < static_cast<int>(_edge_maps.size()); ++i) {
std::map<std::string, int>::iterator jt =
maps.find(_edge_maps[i].first);
if (jt == maps.end()) {
std::ostringstream msg;
msg << "Map not found: " << _edge_maps[i].first;
throw FormatError(msg.str());
}
map_index[i] = jt->second;
}
{
std::map<std::string, int>::iterator jt = maps.find("label");
if (jt != maps.end()) {
label_index = jt->second;
} else {
label_index = -1;
}
}
map_num = maps.size();
}
while (readLine() && line >> c && c != '@') {
line.putback(c);
std::string source_token;
std::string target_token;
if (!_reader_bits::readToken(line, source_token))
throw FormatError("Node u not found");
if (!_reader_bits::readToken(line, target_token))
throw FormatError("Node v not found");
std::vector<std::string> tokens(map_num);
for (int i = 0; i < map_num; ++i) {
if (!_reader_bits::readToken(line, tokens[i])) {
std::ostringstream msg;
msg << "Column not found (" << i + 1 << ")";
throw FormatError(msg.str());
}
}
if (line >> std::ws >> c)
throw FormatError("Extra character at the end of line");
Edge e;
if (!_use_edges) {
typename NodeIndex::iterator it;
it = _node_index.find(source_token);
if (it == _node_index.end()) {
std::ostringstream msg;
msg << "Item not found: " << source_token;
throw FormatError(msg.str());
}
Node source = it->second;
it = _node_index.find(target_token);
if (it == _node_index.end()) {
std::ostringstream msg;
msg << "Item not found: " << target_token;
throw FormatError(msg.str());
}
Node target = it->second;
e = _graph.addEdge(source, target);
if (label_index != -1)
_edge_index.insert(std::make_pair(tokens[label_index], e));
} else {
if (label_index == -1)
throw FormatError("Label map not found");
typename std::map<std::string, Edge>::iterator it =
_edge_index.find(tokens[label_index]);
if (it == _edge_index.end()) {
std::ostringstream msg;
msg << "Edge with label not found: " << tokens[label_index];
throw FormatError(msg.str());
}
e = it->second;
}
for (int i = 0; i < static_cast<int>(_edge_maps.size()); ++i) {
_edge_maps[i].second->set(e, tokens[map_index[i]]);
}
}
if (readSuccess()) {
line.putback(c);
}
}
void readAttributes() {
std::set<std::string> read_attr;
char c;
while (readLine() && line >> c && c != '@') {
line.putback(c);
std::string attr, token;
if (!_reader_bits::readToken(line, attr))
throw FormatError("Attribute name not found");
if (!_reader_bits::readToken(line, token))
throw FormatError("Attribute value not found");
if (line >> c)
throw FormatError("Extra character at the end of line");
{
std::set<std::string>::iterator it = read_attr.find(attr);
if (it != read_attr.end()) {
std::ostringstream msg;
msg << "Multiple occurence of attribute: " << attr;
throw FormatError(msg.str());
}
read_attr.insert(attr);
}
{
typename Attributes::iterator it = _attributes.lower_bound(attr);
while (it != _attributes.end() && it->first == attr) {
it->second->set(token);
++it;
}
}
}
if (readSuccess()) {
line.putback(c);
}
for (typename Attributes::iterator it = _attributes.begin();
it != _attributes.end(); ++it) {
if (read_attr.find(it->first) == read_attr.end()) {
std::ostringstream msg;
msg << "Attribute not found: " << it->first;
throw FormatError(msg.str());
}
}
}
public:
/// \name Execution of the Reader
/// @{
/// \brief Start the batch processing
///
/// This function starts the batch processing
void run() {
LEMON_ASSERT(_is != 0, "This reader assigned to an other reader");
bool nodes_done = _skip_nodes;
bool edges_done = _skip_edges;
bool attributes_done = false;
line_num = 0;
readLine();
skipSection();
while (readSuccess()) {
try {
char c;
std::string section, caption;
line >> c;
_reader_bits::readToken(line, section);
_reader_bits::readToken(line, caption);
if (line >> c)
throw FormatError("Extra character at the end of line");
if (section == "nodes" && !nodes_done) {
if (_nodes_caption.empty() || _nodes_caption == caption) {
readNodes();
nodes_done = true;
}
} else if ((section == "edges" || section == "arcs") &&
!edges_done) {
if (_edges_caption.empty() || _edges_caption == caption) {
readEdges();
edges_done = true;
}
} else if (section == "attributes" && !attributes_done) {
if (_attributes_caption.empty() || _attributes_caption == caption) {
readAttributes();
attributes_done = true;
}
} else {
readLine();
skipSection();
}
} catch (FormatError& error) {
error.line(line_num);
error.file(_filename);
throw;
}
}
if (!nodes_done) {
throw FormatError("Section @nodes not found");
}
if (!edges_done) {
throw FormatError("Section @edges not found");
}
if (!attributes_done && !_attributes.empty()) {
throw FormatError("Section @attributes not found");
}
}
/// @}
};
/// \ingroup lemon_io
///
/// \brief Return a \ref GraphReader class
///
/// This function just returns a \ref GraphReader class.
///
/// With this function a graph can be read from an
/// \ref lgf-format "LGF" file or input stream with several maps and
/// attributes. For example, there is weighted matching problem on a
/// graph, i.e. a graph with a \e weight map on the edges. This
/// graph can be read with the following code:
///
///\code
///ListGraph graph;
///ListGraph::EdgeMap<int> weight(graph);
///graphReader(graph, std::cin).
/// edgeMap("weight", weight).
/// run();
///\endcode
///
/// For a complete documentation, please see the \ref GraphReader
/// class documentation.
/// \warning Don't forget to put the \ref GraphReader::run() "run()"
/// to the end of the parameter list.
/// \relates GraphReader
/// \sa graphReader(TGR& graph, const std::string& fn)
/// \sa graphReader(TGR& graph, const char* fn)
template <typename TGR>
GraphReader<TGR> graphReader(TGR& graph, std::istream& is) {
GraphReader<TGR> tmp(graph, is);
return tmp;
}
/// \brief Return a \ref GraphReader class
///
/// This function just returns a \ref GraphReader class.
/// \relates GraphReader
/// \sa graphReader(TGR& graph, std::istream& is)
template <typename TGR>
GraphReader<TGR> graphReader(TGR& graph, const std::string& fn) {
GraphReader<TGR> tmp(graph, fn);
return tmp;
}
/// \brief Return a \ref GraphReader class
///
/// This function just returns a \ref GraphReader class.
/// \relates GraphReader
/// \sa graphReader(TGR& graph, std::istream& is)
template <typename TGR>
GraphReader<TGR> graphReader(TGR& graph, const char* fn) {
GraphReader<TGR> tmp(graph, fn);
return tmp;
}
class SectionReader;
SectionReader sectionReader(std::istream& is);
SectionReader sectionReader(const std::string& fn);
SectionReader sectionReader(const char* fn);
/// \ingroup lemon_io
///
/// \brief Section reader class
///
/// In the \ref lgf-format "LGF" file extra sections can be placed,
/// which contain any data in arbitrary format. Such sections can be
/// read with this class. A reading rule can be added to the class
/// with two different functions. With the \c sectionLines() function a
/// functor can process the section line-by-line, while with the \c
/// sectionStream() member the section can be read from an input
/// stream.
class SectionReader {
private:
std::istream* _is;
bool local_is;
std::string _filename;
typedef std::map<std::string, _reader_bits::Section*> Sections;
Sections _sections;
int line_num;
std::istringstream line;
public:
/// \brief Constructor
///
/// Construct a section reader, which reads from the given input
/// stream.
SectionReader(std::istream& is)
: _is(&is), local_is(false) {}
/// \brief Constructor
///
/// Construct a section reader, which reads from the given file.
SectionReader(const std::string& fn)
: _is(new std::ifstream(fn.c_str())), local_is(true),
_filename(fn) {
if (!(*_is)) {
delete _is;
throw IoError("Cannot open file", fn);
}
}
/// \brief Constructor
///
/// Construct a section reader, which reads from the given file.
SectionReader(const char* fn)
: _is(new std::ifstream(fn)), local_is(true),
_filename(fn) {
if (!(*_is)) {
delete _is;
throw IoError("Cannot open file", fn);
}
}
/// \brief Destructor
~SectionReader() {
for (Sections::iterator it = _sections.begin();
it != _sections.end(); ++it) {
delete it->second;
}
if (local_is) {
delete _is;
}
}
private:
friend SectionReader sectionReader(std::istream& is);
friend SectionReader sectionReader(const std::string& fn);
friend SectionReader sectionReader(const char* fn);
SectionReader(SectionReader& other)
: _is(other._is), local_is(other.local_is) {
other._is = 0;
other.local_is = false;
_sections.swap(other._sections);
}
SectionReader& operator=(const SectionReader&);
public:
/// \name Section Readers
/// @{
/// \brief Add a section processor with line oriented reading
///
/// The first parameter is the type descriptor of the section, the
/// second is a functor, which takes just one \c std::string
/// parameter. At the reading process, each line of the section
/// will be given to the functor object. However, the empty lines
/// and the comment lines are filtered out, and the leading
/// whitespaces are trimmed from each processed string.
///
/// For example, let's see a section, which contain several
/// integers, which should be inserted into a vector.
///\code
/// @numbers
/// 12 45 23
/// 4
/// 23 6
///\endcode
///
/// The functor is implemented as a struct:
///\code
/// struct NumberSection {
/// std::vector<int>& _data;
/// NumberSection(std::vector<int>& data) : _data(data) {}
/// void operator()(const std::string& line) {
/// std::istringstream ls(line);
/// int value;
/// while (ls >> value) _data.push_back(value);
/// }
/// };
///
/// // ...
///
/// reader.sectionLines("numbers", NumberSection(vec));
///\endcode
template <typename Functor>
SectionReader& sectionLines(const std::string& type, Functor functor) {
LEMON_ASSERT(!type.empty(), "Type is empty.");
LEMON_ASSERT(_sections.find(type) == _sections.end(),
"Multiple reading of section.");
_sections.insert(std::make_pair(type,
new _reader_bits::LineSection<Functor>(functor)));
return *this;
}
/// \brief Add a section processor with stream oriented reading
///
/// The first parameter is the type of the section, the second is
/// a functor, which takes an \c std::istream& and an \c int&
/// parameter, the latter regard to the line number of stream. The
/// functor can read the input while the section go on, and the
/// line number should be modified accordingly.
template <typename Functor>
SectionReader& sectionStream(const std::string& type, Functor functor) {
LEMON_ASSERT(!type.empty(), "Type is empty.");
LEMON_ASSERT(_sections.find(type) == _sections.end(),
"Multiple reading of section.");
_sections.insert(std::make_pair(type,
new _reader_bits::StreamSection<Functor>(functor)));
return *this;
}
/// @}
private:
bool readLine() {
std::string str;
while(++line_num, std::getline(*_is, str)) {
line.clear(); line.str(str);
char c;
if (line >> std::ws >> c && c != '#') {
line.putback(c);
return true;
}
}
return false;
}
bool readSuccess() {
return static_cast<bool>(*_is);
}
void skipSection() {
char c;
while (readSuccess() && line >> c && c != '@') {
readLine();
}
if (readSuccess()) {
line.putback(c);
}
}
public:
/// \name Execution of the Reader
/// @{
/// \brief Start the batch processing
///
/// This function starts the batch processing.
void run() {
LEMON_ASSERT(_is != 0, "This reader assigned to an other reader");
std::set<std::string> extra_sections;
line_num = 0;
readLine();
skipSection();
while (readSuccess()) {
try {
char c;
std::string section, caption;
line >> c;
_reader_bits::readToken(line, section);
_reader_bits::readToken(line, caption);
if (line >> c)
throw FormatError("Extra character at the end of line");
if (extra_sections.find(section) != extra_sections.end()) {
std::ostringstream msg;
msg << "Multiple occurence of section: " << section;
throw FormatError(msg.str());
}
Sections::iterator it = _sections.find(section);
if (it != _sections.end()) {
extra_sections.insert(section);
it->second->process(*_is, line_num);
}
readLine();
skipSection();
} catch (FormatError& error) {
error.line(line_num);
error.file(_filename);
throw;
}
}
for (Sections::iterator it = _sections.begin();
it != _sections.end(); ++it) {
if (extra_sections.find(it->first) == extra_sections.end()) {
std::ostringstream os;
os << "Cannot find section: " << it->first;
throw FormatError(os.str());
}
}
}
/// @}
};
/// \ingroup lemon_io
///
/// \brief Return a \ref SectionReader class
///
/// This function just returns a \ref SectionReader class.
///
/// Please see SectionReader documentation about the custom section
/// input.
///
/// \relates SectionReader
/// \sa sectionReader(const std::string& fn)
/// \sa sectionReader(const char *fn)
inline SectionReader sectionReader(std::istream& is) {
SectionReader tmp(is);
return tmp;
}
/// \brief Return a \ref SectionReader class
///
/// This function just returns a \ref SectionReader class.
/// \relates SectionReader
/// \sa sectionReader(std::istream& is)
inline SectionReader sectionReader(const std::string& fn) {
SectionReader tmp(fn);
return tmp;
}
/// \brief Return a \ref SectionReader class
///
/// This function just returns a \ref SectionReader class.
/// \relates SectionReader
/// \sa sectionReader(std::istream& is)
inline SectionReader sectionReader(const char* fn) {
SectionReader tmp(fn);
return tmp;
}
/// \ingroup lemon_io
///
/// \brief Reader for the contents of the \ref lgf-format "LGF" file
///
/// This class can be used to read the sections, the map names and
/// the attributes from a file. Usually, the LEMON programs know
/// that, which type of graph, which maps and which attributes
/// should be read from a file, but in general tools (like glemon)
/// the contents of an LGF file should be guessed somehow. This class
/// reads the graph and stores the appropriate information for
/// reading the graph.
///
///\code
/// LgfContents contents("graph.lgf");
/// contents.run();
///
/// // Does it contain any node section and arc section?
/// if (contents.nodeSectionNum() == 0 || contents.arcSectionNum()) {
/// std::cerr << "Failure, cannot find graph." << std::endl;
/// return -1;
/// }
/// std::cout << "The name of the default node section: "
/// << contents.nodeSection(0) << std::endl;
/// std::cout << "The number of the arc maps: "
/// << contents.arcMaps(0).size() << std::endl;
/// std::cout << "The name of second arc map: "
/// << contents.arcMaps(0)[1] << std::endl;
///\endcode
class LgfContents {
private:
std::istream* _is;
bool local_is;
std::vector<std::string> _node_sections;
std::vector<std::string> _edge_sections;
std::vector<std::string> _attribute_sections;
std::vector<std::string> _extra_sections;
std::vector<bool> _arc_sections;
std::vector<std::vector<std::string> > _node_maps;
std::vector<std::vector<std::string> > _edge_maps;
std::vector<std::vector<std::string> > _attributes;
int line_num;
std::istringstream line;
public:
/// \brief Constructor
///
/// Construct an \e LGF contents reader, which reads from the given
/// input stream.
LgfContents(std::istream& is)
: _is(&is), local_is(false) {}
/// \brief Constructor
///
/// Construct an \e LGF contents reader, which reads from the given
/// file.
LgfContents(const std::string& fn)
: _is(new std::ifstream(fn.c_str())), local_is(true) {
if (!(*_is)) {
delete _is;
throw IoError("Cannot open file", fn);
}
}
/// \brief Constructor
///
/// Construct an \e LGF contents reader, which reads from the given
/// file.
LgfContents(const char* fn)
: _is(new std::ifstream(fn)), local_is(true) {
if (!(*_is)) {
delete _is;
throw IoError("Cannot open file", fn);
}
}
/// \brief Destructor
~LgfContents() {
if (local_is) delete _is;
}
private:
LgfContents(const LgfContents&);
LgfContents& operator=(const LgfContents&);
public:
/// \name Node Sections
/// @{
/// \brief Gives back the number of node sections in the file.
///
/// Gives back the number of node sections in the file.
int nodeSectionNum() const {
return _node_sections.size();
}
/// \brief Returns the node section name at the given position.
///
/// Returns the node section name at the given position.
const std::string& nodeSection(int i) const {
return _node_sections[i];
}
/// \brief Gives back the node maps for the given section.
///
/// Gives back the node maps for the given section.
const std::vector<std::string>& nodeMapNames(int i) const {
return _node_maps[i];
}
/// @}
/// \name Arc/Edge Sections
/// @{
/// \brief Gives back the number of arc/edge sections in the file.
///
/// Gives back the number of arc/edge sections in the file.
/// \note It is synonym of \c edgeSectionNum().
int arcSectionNum() const {
return _edge_sections.size();
}
/// \brief Returns the arc/edge section name at the given position.
///
/// Returns the arc/edge section name at the given position.
/// \note It is synonym of \c edgeSection().
const std::string& arcSection(int i) const {
return _edge_sections[i];
}
/// \brief Gives back the arc/edge maps for the given section.
///
/// Gives back the arc/edge maps for the given section.
/// \note It is synonym of \c edgeMapNames().
const std::vector<std::string>& arcMapNames(int i) const {
return _edge_maps[i];
}
/// @}
/// \name Synonyms
/// @{
/// \brief Gives back the number of arc/edge sections in the file.
///
/// Gives back the number of arc/edge sections in the file.
/// \note It is synonym of \c arcSectionNum().
int edgeSectionNum() const {
return _edge_sections.size();
}
/// \brief Returns the section name at the given position.
///
/// Returns the section name at the given position.
/// \note It is synonym of \c arcSection().
const std::string& edgeSection(int i) const {
return _edge_sections[i];
}
/// \brief Gives back the edge maps for the given section.
///
/// Gives back the edge maps for the given section.
/// \note It is synonym of \c arcMapNames().
const std::vector<std::string>& edgeMapNames(int i) const {
return _edge_maps[i];
}
/// @}
/// \name Attribute Sections
/// @{
/// \brief Gives back the number of attribute sections in the file.
///
/// Gives back the number of attribute sections in the file.
int attributeSectionNum() const {
return _attribute_sections.size();
}
/// \brief Returns the attribute section name at the given position.
///
/// Returns the attribute section name at the given position.
const std::string& attributeSectionNames(int i) const {
return _attribute_sections[i];
}
/// \brief Gives back the attributes for the given section.
///
/// Gives back the attributes for the given section.
const std::vector<std::string>& attributes(int i) const {
return _attributes[i];
}
/// @}
/// \name Extra Sections
/// @{
/// \brief Gives back the number of extra sections in the file.
///
/// Gives back the number of extra sections in the file.
int extraSectionNum() const {
return _extra_sections.size();
}
/// \brief Returns the extra section type at the given position.
///
/// Returns the section type at the given position.
const std::string& extraSection(int i) const {
return _extra_sections[i];
}
/// @}
private:
bool readLine() {
std::string str;
while(++line_num, std::getline(*_is, str)) {
line.clear(); line.str(str);
char c;
if (line >> std::ws >> c && c != '#') {
line.putback(c);
return true;
}
}
return false;
}
bool readSuccess() {
return static_cast<bool>(*_is);
}
void skipSection() {
char c;
while (readSuccess() && line >> c && c != '@') {
readLine();
}
if (readSuccess()) {
line.putback(c);
}
}
void readMaps(std::vector<std::string>& maps) {
char c;
if (!readLine() || !(line >> c) || c == '@') {
if (readSuccess() && line) line.putback(c);
return;
}
line.putback(c);
std::string map;
while (_reader_bits::readToken(line, map)) {
maps.push_back(map);
}
}
void readAttributes(std::vector<std::string>& attrs) {
readLine();
char c;
while (readSuccess() && line >> c && c != '@') {
line.putback(c);
std::string attr;
_reader_bits::readToken(line, attr);
attrs.push_back(attr);
readLine();
}
line.putback(c);
}
public:
/// \name Execution of the Contents Reader
/// @{
/// \brief Starts the reading
///
/// This function starts the reading.
void run() {
readLine();
skipSection();
while (readSuccess()) {
char c;
line >> c;
std::string section, caption;
_reader_bits::readToken(line, section);
_reader_bits::readToken(line, caption);
if (section == "nodes") {
_node_sections.push_back(caption);
_node_maps.push_back(std::vector<std::string>());
readMaps(_node_maps.back());
readLine(); skipSection();
} else if (section == "arcs" || section == "edges") {
_edge_sections.push_back(caption);
_arc_sections.push_back(section == "arcs");
_edge_maps.push_back(std::vector<std::string>());
readMaps(_edge_maps.back());
readLine(); skipSection();
} else if (section == "attributes") {
_attribute_sections.push_back(caption);
_attributes.push_back(std::vector<std::string>());
readAttributes(_attributes.back());
} else {
_extra_sections.push_back(section);
readLine(); skipSection();
}
}
}
/// @}
};
}
#endif