1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
|
%* gmpl.tex *%
%***********************************************************************
% This code is part of GLPK (GNU Linear Programming Kit).
%
% Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008,
% 2009, 2010, 2011, 2013, 2014, 2015 Andrew Makhorin, Department for
% Applied Informatics, Moscow Aviation Institute, Moscow, Russia. All
% rights reserved. E-mail: <mao@gnu.org>.
%
% GLPK is free software: you can redistribute it and/or modify it
% under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% GLPK is distributed in the hope that it will be useful, but WITHOUT
% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
% or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
% License for more details.
%
% You should have received a copy of the GNU General Public License
% along with GLPK. If not, see <http://www.gnu.org/licenses/>.
%***********************************************************************
\documentclass[11pt, brazil]{report}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{amssymb}
\usepackage[dvipdfm,linktocpage,colorlinks,linkcolor=blue,
urlcolor=blue]{hyperref}
\usepackage{indentfirst}
\setlength{\textwidth}{6.5in}
\setlength{\textheight}{8.5in}
\setlength{\oddsidemargin}{0in}
\setlength{\topmargin}{0in}
\setlength{\headheight}{0in}
\setlength{\headsep}{0in}
\setlength{\footskip}{0.5in}
\setlength{\parindent}{16pt}
\setlength{\parskip}{5pt}
\setlength{\topsep}{0pt}
\setlength{\partopsep}{0pt}
\setlength{\itemsep}{\parskip}
\setlength{\parsep}{0pt}
\setlength{\leftmargini}{\parindent}
\renewcommand{\labelitemi}{---}
\def\para#1{\noindent{\bf#1}}
\renewcommand\contentsname{\sf\bfseries Conteúdo}
\renewcommand\chaptername{\sf\bfseries Capítulo}
\renewcommand\appendixname{\sf\bfseries Apêndice}
% \renewcommand\contentsname{\sf\bfseries Contents}
% \renewcommand\chaptername{\sf\bfseries Chapter}
% \renewcommand\appendixname{\sf\bfseries Appendix}
\begin{document}
\thispagestyle{empty}
\begin{center}
\vspace*{1.5in}
\begin{huge}
\sf\bfseries Linguagem de Modelagem GNU MathProg
\end{huge}
\vspace{0.5in}
\begin{LARGE}
\sf Linguagem de Referência % Language Reference
\end{LARGE}
\vspace{0.5in}
\begin{LARGE}
\sf para o GLPK Versão 4.57
\end{LARGE}
\vspace{0.5in}
\begin{Large}
\sf (RASCUNHO, Fevereiro 2016)
\end{Large}
\end{center}
\newpage
\vspace*{1in}
\vfill
\noindent
% The GLPK package is part of the GNU Project released under the aegis of GNU.
O pacote GLPK é parte do Projeto GNU distribuído sob a égide do GNU.
\noindent
Copyright \copyright{} 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007,
2008, 2009, 2010, 2011, 2013, 2014, 2015, 2016 Andrew Makhorin, Department
for Applied Informatics, Moscow Aviation Institute, Moscow, Russia.
% All rights reserved.
Todos os direitos reservados.
\noindent
Título original: Modeling Language GNU MathProg - Language Reference for GLPK Version 4.57
\noindent
Tradução: João Flávio de Freitas Almeida, Departamento de Engenharia de Produção, Universidade Federal de Minas Gerais,
Minas Gerais, Brasil.
\noindent
Copyright \copyright{} 2015 João Flávio de Freitas Almeida, para esta tradução. Todos os direitos reservados.
\noindent
Free Software Foundation, Inc., Rua Franklin, 51, 5$^{o}$ andar, Boston,
MA 02110-1301, USA.
\noindent
É permitido realizar e distribuir cópias textuais deste manual
mantendo o aviso de copyright e preservando este aviso de permissão
em todas as cópias.
% Permission is granted to make and distribute verbatim copies of this
% manual provided the copyright notice and this permission notice are
% preserved on all copies.
\noindent
É concedida a permissão para copiar e distribuir versões modificadas deste manual sob
as condições de cópias textuais, desde que o resultado completo derivado
do trabalho resultante seja distribuído sob os termos de uma notificação
de permissão idêntica a esta.
% Permission is granted to copy and distribute modified versions of this
% manual under the conditions for verbatim copying, provided also that
% the entire resulting derived work is distributed under the terms of
% a permission notice identical to this one.
\noindent
É concedida a permissão para copiar e distribuir traduções deste manual
em outra linguagem, sob as condições acima para as versões modificadas.
% Permission is granted to copy and distribute translations of this
% manual into another language, under the above conditions for modified
% versions.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\newpage
{\setlength{\parskip}{0pt}
\tableofcontents
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\chapter{Introdução}
{\it GNU MathProg} é uma linguagem de modelagem projetada para descrever
modelos lineares de programação matemática.
\footnote{A linguagem GNU MathProg é um subconjunto da linguagem AMPL.
A implementação do GLPK é \linebreak principalmente baseada no artigo:
{\it Robert Fourer}, {\it David M. Gay}, and
{\it Brian W. Kernighan}, ``A Modeling Language for Mathematical
Programming.'' {\it Management Science} 36 (1990), pp.~519-54.}
% {\it GNU MathProg} is a modeling language intended for describing
% linear mathematical programming models.\footnote{The GNU MathProg
% language is a subset of the AMPL language. Its GLPK implementation is
% mainly based on the paper: {\it Robert Fourer}, {\it David M. Gay}, and
% {\it Brian W. Kernighan}, ``A Modeling Language for Mathematical
% Programming.'' {\it Management Science} 36 (1990), pp.~519-54.}
A descrição de um modelo escrito na linguagem GNU MathProg consiste
em um conjunto de sentenças e blocos de dados construído pelo
usuário a partir dos elementos de linguagem descritos neste documento.
% Model descriptions written in the GNU MathProg language consist of
% a set of statements and data blocks constructed by the user from the
% language elements described in this document.
Em um processo denominado {\it tradução}, um programa denominado
{\it tradutor do modelo} analisa a descrição do modelo e o traduz
para uma estrutura de dados interna, que pode ser usado tanto para gerar
instância de um problema de programação matemática ou obter diretamente
a solução numérica do problema por meio de um programa chamado {\it solver}.
% In a process called {\it translation}, a program called the {\it model
% translator} analyzes the model description and translates it into
% internal data structures, which may be then used either for generating
% mathematical programming problem instance or directly by a program
% called the {\it solver} to obtain numeric solution of the problem.
\section{Problema de programação linear}
\label{problem}
Em MathProg o problema de programação linear (PL) é expresso da seguinte forma:
% In MathProg the linear programming (LP) problem is stated as follows:
\medskip
\noindent\hspace{1in}minimizar (ou maximizar)
$$z=c_1x_1+c_2x_2+\dots+c_nx_n+c_0\eqno(1.1)$$
\noindent\hspace{1in}subjeito às restrições lineares
$$
\begin{array}{l@{\ }c@{\ }r@{\ }c@{\ }r@{\ }c@{\ }r@{\ }c@{\ }l}
L_1&\leq&a_{11}x_1&+&a_{12}x_2&+\dots+&a_{1n}x_n&\leq&U_1\\
L_2&\leq&a_{21}x_1&+&a_{22}x_2&+\dots+&a_{2n}x_n&\leq&U_2\\
\multicolumn{9}{c}{.\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .}\\
L_m&\leq&a_{m1}x_1&+&a_{m2}x_2&+\dots+&a_{mn}x_n&\leq&U_m\\
\end{array}\eqno(1.2)
$$
\noindent\hspace{1in}e os limites das variáveis
$$
\begin{array}{l@{\ }c@{\ }c@{\ }c@{\ }l}
l_1&\leq&x_1&\leq&u_1\\
l_2&\leq&x_2&\leq&u_2\\
\multicolumn{5}{c}{.\ \ .\ \ .\ \ .\ \ .}\\
l_n&\leq&x_n&\leq&u_n\\
\end{array}\eqno(1.3)
$$
% \newpage
\noindent
onde $x_1$, $x_2$, \dots, $x_n$ são variáveis; $z$ é a função objetivo
; $c_1$, $c_2$, \dots, $c_n$ são coeficientes da função objetivo; $c_0$
é o termo constante da função objetivo; $a_{11}$,
$a_{12}$, \dots, $a_{mn}$ são coeficientes das restrições; $L_1$, $L_2$,
\dots, $L_m$ são limites inferiores das restrições; $U_1$, $U_2$, \dots, $U_m$
são limites superiores das restrições; $l_1$, $l_2$, \dots, $l_n$ são limites
inferiores das variáveis; $u_1$, $u_2$, \dots, $u_n$ são limites superiores das
variáveis.
Os limites das variáveis e das restrições podem ser tanto finitos quanto
infinitos. Além disso, os limites inferiores podem ser igual aos limites
superiores correspondentes. Logo, os seguintes tipos de variáveis e
restrições são permitidos:
% where $x_1$, $x_2$, \dots, $x_n$ are variables; $z$ is the objective
% function; $c_1$, $c_2$, \dots, $c_n$ are objective coefficients; $c_0$
% is the constant term (``shift'') of the objective function; $a_{11}$,
% $a_{12}$, \dots, $a_{mn}$ are constraint coefficients; $L_1$, $L_2$,
% \dots, $L_m$ are lower constraint bounds; $U_1$, $U_2$, \dots, $U_m$
% are upper constraint bounds; $l_1$, $l_2$, \dots, $l_n$ are lower
% bounds of variables; $u_1$, $u_2$, \dots, $u_n$ are upper bounds of
% variables.
%
% Bounds of variables and constraint bounds can be finite as well as
% infinite. Besides, lower bounds can be equal to corresponding upper
% bounds. Thus, the following types of variables and constraints are
% allowed:
\medskip
{\def\arraystretch{1.4}
\noindent\hspace{54pt}
\begin{tabular}{@{}r@{\ }c@{\ }c@{\ }c@{\ }l@{\hspace*{39.5pt}}l}
$-\infty$&$<$&$x$&$<$&$+\infty$&Variável livre (ilimitada)\\
$l$&$\leq$&$x$&$<$&$+\infty$&Variável com limite inferior\\
$-\infty$&$<$&$x$&$\leq$&$u$&Variável com limite superior\\
$l$&$\leq$&$x$&$\leq$&$u$&Variável duplamente limitada\\
$l$&$=$&$x$&=&$u$&Variável fixa\\
\end{tabular}
% \begin{tabular}{@{}r@{\ }c@{\ }c@{\ }c@{\ }l@{\hspace*{39.5pt}}l}
% $-\infty$&$<$&$x$&$<$&$+\infty$&Free (unbounded) variable\\
% $l$&$\leq$&$x$&$<$&$+\infty$&Variable with lower bound\\
% $-\infty$&$<$&$x$&$\leq$&$u$&Variable with upper bound\\
% $l$&$\leq$&$x$&$\leq$&$u$&Double-bounded variable\\
% $l$&$=$&$x$&=&$u$&Fixed variable\\
% \end{tabular}
\noindent\hfil
\begin{tabular}{@{}r@{\ }c@{\ }c@{\ }c@{\ }ll}
$-\infty$&$<$&$\sum a_jx_j$&$<$&$+\infty$&Forma linear livre (ilimitada)\\
$L$&$\leq$&$\sum a_jx_j$&$<$&$+\infty$&Restrição de desigualdade ``maior ou igual a''\\
$-\infty$&$<$&$\sum a_jx_j$&$\leq$&$U$&Restrição de desigualdade ``menor ou igual a''\\
$L$&$\leq$&$\sum a_jx_j$&$\leq$&$U$&Restrição de desigualdade duplamente limitada\\
$L$&$=$&$\sum a_jx_j$&=&$U$&Restrição de igualdade\\
\end{tabular}
% \begin{tabular}{@{}r@{\ }c@{\ }c@{\ }c@{\ }ll}
% $-\infty$&$<$&$\sum a_jx_j$&$<$&$+\infty$&Free (unbounded) linear
% form\\
% $L$&$\leq$&$\sum a_jx_j$&$<$&$+\infty$&Inequality constraint ``greater
% than or equal to''\\
% $-\infty$&$<$&$\sum a_jx_j$&$\leq$&$U$&Inequality constraint ``less
% than or equal to''\\
% $L$&$\leq$&$\sum a_jx_j$&$\leq$&$U$&Double-bounded inequality
% constraint\\
% $L$&$=$&$\sum a_jx_j$&=&$U$&Equality constraint\\
% \end{tabular}
}
\medskip
Além de problemas puramente PL, MathProg também permite
problemas de programação inteira mista (PIM), onde algumas ou
todas as variáveis são restritas a serem inteiras ou binárias.
% In addition to pure LP problems MathProg also allows mixed integer
% linear programming (MIP) problems, where some or all variables are
% restricted to be integer or binary.
\section{Objetos do modelo}
Em MathProg o modelo é descrito em termos de conjuntos, parâmetros,
variáveis, restrições e objetivos, que se denominam {\it objetos
do modelo}.
O usuário introduz objetos particulares do modelo usando as sentenças
da linguagem. Cada objeto do modelo possui um nome simbólico que o identifica
de maneira única sendo projetado para propósitos de referenciação.
% In MathProg the model is described in terms of sets, parameters,
% variables, constraints, and objectives, which are called {\it model
% objects}.
%
% The user introduces particular model objects using the language
% statements. Each model object is provided with a symbolic name which
% uniquely identifies the object and is intended for referencing
% purposes.
Objetos do modelo, incluindo conjuntos, podem ser matrizes multidimensionais
construídos sobre conjuntos indexantes. Formalmente, uma matriz $n$-dimensional $A$
é o mapeamento:
% Model objects, including sets, can be multidimensional arrays built
% over indexing sets. Formally, $n$-dimensional array $A$ is the mapping:
$$A:\Delta\rightarrow\Xi,\eqno(1.4)$$
onde $\Delta\subseteq S_1\times\dots\times S_n$ é um subconjunto do
produto Cartesiano de conjuntos indexantes, $\Xi$ é um conjunto dos
membros da matriz. Em MathProg o conjunto $\Delta$ é chamado o {\it domínio do subíndice}. % REVISAR
Seus membros são $n$-tuplas $(i_1,\dots,i_n)$, onde $i_1\in S_1$, \dots,
$i_n\in S_n$.
% where $\Delta\subseteq S_1\times\dots\times S_n$ is a subset of the
% Cartesian product of indexing sets, $\Xi$ is a set of array members.
% In MathProg the set $\Delta$ is called the {\it subscript domain}. Its
% members are $n$-tuples $(i_1,\dots,i_n)$, where $i_1\in S_1$, \dots,
% $i_n\in S_n$.
Se $n=0$, o produto Cartesiano acima possui exatamente um membro (denominado
0-tupla), portanto, é conveniente pensar nos objetos escalares como sendo
matrizes 0-dimensionais que \linebreak possuem apenas um membro.
% If $n=0$, the Cartesian product above has exactly one member (namely,
% 0-tuple), so it is convenient to think scalar objects as 0-dimensional
% arrays having one member.
% \newpage
O tipo dos membros da matriz é determinado pelo tipo de objeto do modelo
correspondente, como segue:
% The type of array members is determined by the type of corresponding
% model object as follows:
\medskip
\noindent\hfil
\begin{tabular}{@{}ll@{}}
Objeto do modelo&Membro da matriz\\
\hline
Conjunto&Conjunto plano elementar\\
Parâmetro&Número ou símbolo\\
Variável&Variável elementar\\
Restrição&Restrição elementar\\
Objetivo&Objetivo elementar\\
\end{tabular}
% \begin{tabular}{@{}ll@{}}
% Model object&Array member\\
% \hline
% Set&Elemental plain set\\
% Parameter&Number or symbol\\
% Variable&Elemental variable\\
% Constraint&Elemental constraint\\
% Objective&Elemental objective\\
% \end{tabular}
\medskip
Para referir a um membro particular de um objeto, este deve possuir
{\it subíndices}. Por exemplo, se $a$ é um parâmetro 2-dimensional
definido sobre $I\times J$, uma referência a seus membros particulares
pode ser escrito como $a[i,j]$, onde $i\in I$ e $j\in J$. Entende-se
que objetos escalares não necessitam de subíndices por serem 0-dimensionais.
% In order to refer to a particular object member the object should be
% provided with {\it subscripts}. For example, if $a$ is a 2-dimensional
% parameter defined over $I\times J$, a reference to its particular
% member can be written as $a[i,j]$, where $i\in I$ and $j\in J$. It is
% understood that scalar objects being 0-dimensional need no subscripts.
\section{Estrutura da descrição do modelo}
Às vezes é desejável escrever um modelo que, por diferentes motivos,
tenha que requerer diferentes dados para resolver cada instância do problema
usando o mesmo modelo.
Por esta razão, em MathProg a descrição do modelo consiste em duas partes:
a {\it seção de modelo} e a {\it seção de dados}.
% It is sometimes desirable to write a model which, at various points,
% may require different data for each problem instance to be solved using
% that model. For this reason in MathProg the model description consists
% of two parts: the {\it model section} and the {\it data section}.
A seção de modelo é a principal parte da descrição do modelo, pois ela contém
as declarações dos objetos do modelo. Ela também é comum a todos os problemas
baseados no modelo correspondente.
% The model section is a main part of the model description that contains
% declarations of model objects and is common for all problems based on
% the corresponding model.
A seção de dados é uma parte opcional da descrição do modelo que
contém dados específicos para uma instância particular do problema.
% The data section is an optional part of the model description that
% contains data specific for a particular problem instance.
Dependendo do que seja mais conveniente, as seções de modelo e de dados
podem ser dispostas em um arquivo único ou em dois arquivos separados.
Esta última funcionalidade permite que se tenha um quantidade arbitrária
de seções de dados diferentes a serem usadas com a mesma seção de modelo.
% Depending on what is more convenient the model and data sections can be
% placed either in one file or in two separate files. The latter feature
% allows having arbitrary number of different data sections to be used
% with the same model section.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\chapter{Codificação da descrição do modelo}
\label{coding}
A descrição do modelo é codificada em um formato de arquivo plano de
texto usando o conjunto de caracteres ASCII.
Os caracteres válidos na descrição do modelo são os seguintes:
% The model description is coded in a plain text format using ASCII
% character set. Characters valid in the model description are the
% following:
\begin{itemize}
\item Caracteres alfabéticos:\\
\verb|A B C D E F G H I J K L M N O P Q R S T U V W X Y Z|\\
\verb|a b c d e f g h i j k l m n o p q r s t u v w x y z _|
\item caracteres numéricos:\\
\verb|0 1 2 3 4 5 6 7 8 9|
\item caracteres especiais:\\
\verb?! " # & ' ( ) * + , - . / : ; < = > [ ] ^ { | } ~?
\item caracteres de espaço em branco:\\
\verb|SP HT CR NL VT FF|
\end{itemize}
Dentro de literais de cadeia e comentários quaisquer
caracteres ASCII (exceto caracteres de controle) são válidos.
% Within string literals and comments any ASCII characters (except
% control characters) are valid.
Caracteres de espaço-em-branco não são significativos. Eles podem ser
usados livremente entre unidades léxicas para melhorar a legibilidade da
descrição do modelo. Eles também são usados para separar unidades léxicas
entre si, no caso de não existir outra forma de fazê-lo.
% White-space characters are non-significant. They can be used freely
% between lexical units to improve readability of the model description.
% They are also used to separate lexical units from each other if there
% is no other way to do that.
Sintaticamente a descrição do modelo é uma sequência de unidades léxicas
nas seguintes \linebreak categorias:
% Syntactically model description is a sequence of lexical units in the
% following categories:
\begin{itemize}
\item nomes simbólicos;
\item literais numéricos;
\item literais de cadeia;
\item palavras-chave;
\item delimitadores;
\item comentários.
\end{itemize}
% \begin{itemize}
% \item symbolic names;
% \item numeric literals;
% \item string literals;
% \item keywords;
% \item delimiters;
% \item comments.
% \end{itemize}
As unidades léxicas da linguagem são discutidas abaixo.
% \newpage
\section{Nomes simbólicos}
Um {\it nome simbólico} consiste de caracteres alfabéticos e numéricos,
em que o primeiro deste deve ser alfabético. Todos os nomes simbólicos
devem ser distintos (sensibilidade às maiúsculas: case-sensitive).
% A {\it symbolic name} consists of alphabetic and numeric characters,
% the first of which should be alphabetic. All symbolic names are
% distinct (case sensitive).
\para{Exemplos}
\begin{verbatim}
alfa123
Este_eh_um_nome
_P123_abc_321
\end{verbatim}
Nomes simbólicos são usados para identificar objetos do modelo
(conjuntos, parâmetros, \linebreak variáveis, restrições, objetivos)
e os índices.
% Symbolic names are used to identify model objects (sets, parameters,
% variables, constraints, objectives) and dummy indices.
Todos os nomes simbólicos (exceto os nomes dos índices) devem ser únicos,
i.e., a descrição do modelo não pode ter objetos com nomes idênticos.
Nomes simbólicos de índices devem ser únicos dentro do escopo em que são válidos.
% All symbolic names (except names of dummy indices) should be unique,
% i.e. the model description should have no objects with identical names.
% Symbolic names of dummy indices should be unique within the scope,
% where they are valid.
\section{Literais numéricos}
Um {\it literal numérico} possui a forma {\it xx}{\tt E}{\it syy}, onde
{\it xx} é um número com ponto decimal opcional, {\it s} é o sinal
{\tt+} ou {\tt-}, {\it yy} é um expoente decimal. A letra {\tt E} é
insensível à maiúsculas (case-insensitive) e pode ser codificada como {\tt e}.
% A {\it numeric literal} has the form {\it xx}{\tt E}{\it syy}, where
% {\it xx} is a number with optional decimal point, {\it s} is the sign
% {\tt+} or {\tt-}, {\it yy} is a decimal exponent. The letter {\tt E} is
% case insensitive and can be coded as {\tt e}.
\para{Exemplos}
\begin{verbatim}
123
3.14159
56.E+5
.78
123.456e-7
\end{verbatim}
Literais numéricos são usados para representar quantidades numéricas. Eles
possuem significado fixo óbvio.
% Numeric literals are used to represent numeric quantities. They have
% obvious fixed meaning.
\section{Literais de cadeia}
Uma {\it literal de cadeia} é uma sequência arbitrária de caracteres cercada
por aspas tanto simples como duplas. Ambas formas são equivalentes.
% A {\it string literal} is a sequence of arbitrary characters enclosed
% either in single quotes or in double quotes. Both these forms are
% equivalent.
Se uma aspa simples é parte de uma literal de cadeia cercada por
aspas simples, ela deve ser codificada duas vezes. De forma análoga,
se uma aspa dupla é parte de um literal de cadeia cercada por aspas duplas,
ela deve ser codificada duas vezes.
% If a single quote is part of a string literal enclosed in single
% quotes, it should be coded twice. Analogously, if a double quote is
% part of a string literal enclosed in double quotes, it should be coded
% twice.
\para{Exemplos}
\begin{verbatim}
'Esta eh uma string'
"Esta eh outra string"
'Copo d''agua'
"""Beleza"" disse o capitao."
\end{verbatim}
Literais de cadeia são usadas para representar quantidades simbólicas.
% String literals are used to represent symbolic quantities.
\section{Palavras-chave}
Uma {\it palavra-chave} é uma sequência de caracteres alfabéticos e
possivelmente alguns caracteres especiais.
% A {\it keyword} is a sequence of alphabetic characters and possibly
% some special characters.
Todas as palavras-chave caem em algumas das duas categorias:
{\it palavras-chave reservadas}, que não podem ser usadas como nomes simbólicos,
e {\it palavras-chave não-reservadas}, que são reconhecidas pelo contexto,
portanto, podem ser usadas como nomes simbólicos.
As palavras-chave reservadas são as seguintes:
% All keywords fall into two categories: {\it reserved keywords}, which
% cannot be used as symbolic names, and {\it non-reserved keywords},
% which are recognized by context and therefore can be used as symbolic
% names.
%
% The reserved keywords are the following:
\noindent\hfil
\begin{tabular}{@{}p{.7in}p{.7in}p{.7in}p{.7in}@{}}
{\tt and}&{\tt else}&{\tt mod}&{\tt union}\\
{\tt by}&{\tt if}&{\tt not}&{\tt within}\\
{\tt cross}&{\tt in}&{\tt or}\\
{\tt diff}&{\tt inter}&{\tt symdiff}\\
{\tt div}&{\tt less}&{\tt then}\\
\end{tabular}
Palavras-chave não-reservadas são descritas nas seções posteriores.
Todas as palavras-chave possuem um significado fixo, a ser
explicado nas discussões das \linebreak construções sintáticas correspondentes,
onde as palavras-chave são usadas.
% Non-reserved keywords are described in following sections.
%
% All the keywords have fixed meaning, which will be explained on
% discussion of corresponding syntactic constructions, where the keywords
% are used.
\section{Delimitadores}
Um {\it delimitador} é tanto um caractere especial único quanto uma sequência
de dois caracteres especiais, como segue:
% A {\it delimiter} is either a single special character or a sequence of
% two special characters as follows:
\noindent\hfil
\begin{tabular}{@{}p{.3in}p{.3in}p{.3in}p{.3in}p{.3in}p{.3in}p{.3in}
p{.3in}p{.3in}@{}}
{\tt+}&{\tt**}&{\tt<=}&{\tt>}&{\tt\&\&}&{\tt:}&{\tt|}&{\tt[}&
{\tt>>}\\
{\tt-}&{\tt\textasciicircum}&{\tt=}&{\tt<>}&{\tt||}&{\tt;}&
{\tt\char126}&{\tt]}&{\tt<-}\\
{\tt*}&{\tt\&}&{\tt==}&{\tt!=}&{\tt.}&{\tt:=}&{\tt(}&{\tt\{}\\
{\tt/}&{\tt<}&{\tt>=}&{\tt!}&{\tt,}&{\tt..}&{\tt)}&{\tt\}}\\
\end{tabular}
Se um delimitador consiste de dois caracteres, não deve haver espaços
entre os eles.
Todos os delimitadores possuem um significado fixo, a ser
explicado nas discussões das \linebreak construções sintáticas correspondentes,
onde os delimitadores são usados.
% If the delimiter consists of two characters, there should be no spaces
% between the characters.
%
% All the delimiters have fixed meaning, which will be explained on
% discussion corresponding syntactic constructions, where the delimiters
% are used.
\section{Comentários}
Com propósitos de documentação, a descrição do modelo pode conter
{\it comentários}, que podem ter duas formas diferentes. A primeira forma é
um {\it comentário de linha-única}, que começa com o caractere {\tt\#}
e se estende até o final da linha. A segunda forma é uma {\it sequência de
comentários}, que é uma sequência de quaisquer caracteres cercados por
{\tt/*} e {\tt*/}.
% For documenting purposes the model description can be provided with
% {\it comments}, which may have two different forms. The first form is
% a {\it single-line comment}, which begins with the character {\tt\#}
% and extends until end of line. The second form is a {\it comment
% sequence}, which is a sequence of any characters enclosed within
% {\tt/*} and {\tt*/}.
\para{Exemplos}
\begin{verbatim}
param n := 10; # Este é um comentario
/* Este é outro comentário */
\end{verbatim}
Comentários e caracteres de espaço-em-branco são ignorados pelo tradutor
do modelo e podem aparecer em qualquer local da descrição do modelo.
% Comments are ignored by the model translator and can appear anywhere in
% the model description, where white-space characters are allowed.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\newpage
\chapter{Expressões}
Uma {\it expressão} é uma regra para calcular um valor. Na descrição
de um modelo, expressões são usadas como constituintes de certas sentenças.
No geral, expressões são constituídas de operandos e operadores.
Dependendo do tipo de valor resultante, todas expressões se enquadram nas
seguintes categorias:
% An {\it expression} is a rule for computing a value. In model
% description expressions are used as constituents of certain statements.
%
% In general case expressions consist of operands and operators.
%
% Depending on the type of the resultant value all expressions fall into
% the following categories:
\vspace*{-8pt}
\begin{itemize}
\item expressões numéricas;
\item expressões simbólicas;
\item expressões indexantes;
\item expressões de conjuntos;
\item expressões lógicas;
\item expressões lineares.
\end{itemize}
% \begin{itemize}
% \item numeric expressions;
% \item symbolic expressions;
% \item indexing expressions;
% \item set expressions;
% \item logical expressions;
% \item linear expressions.
% \end{itemize}
\vspace*{-8pt}
\section{Expressões numéricas}
Uma {\it expressão numérica} é uma regra para calcular um valor numérico individual
representado como um número de ponto-flutuante.
A expressão numérica primária pode ser um literal numérico, um índice,
um parâmetro não-indexado, um parâmetro indexado, uma função interna de
referência, uma expressão numérica iterada, uma expressão numérica condicional
ou outra expressão cercada por parênteses.
% A {\it numeric expression} is a rule for computing a single numeric
% value represented as a floating-point number.
%
% The primary numeric expression may be a numeric literal, dummy index,
% unsubscripted parameter, subscripted parameter, built-in function
% reference, iterated numeric expression, conditional numeric expression,
% or another numeric expression enclosed in parentheses.
\para{Exemplos}
\noindent
\begin{tabular}{@{}ll@{}}
\verb|1.23 |&(literal numérico)\\
\verb|j|&(índice)\\
\verb|time|&(parâmetro não-indexado)\\
\verb|a['May 2003',j+1]|&(parâmetro indexado)\\
\verb|abs(b[i,j])|&(função de referência)\\
\end{tabular}
% \begin{tabular}{@{}ll@{}}
% \verb|1.23 |&(numeric literal)\\
% \verb|j|&(dummy index)\\
% \verb|time|&(unsubscripted parameter)\\
% \verb|a['May 2003',j+1]|&(subscripted parameter)\\
% \verb|abs(b[i,j])|&(function reference)\\
% \end{tabular}
\newpage
\noindent
\begin{tabular}{@{}ll@{}}
\verb|sum{i in S diff T} alpha[i] * b[i,j]|&(expressão iterada)\\
\verb|if i in I then 2 * p else q[i+1]|&(expressão condicional)\\
\verb|(b[i,j] + .5 * c)|&(expressão entre parênteses)\\
\end{tabular}
% \begin{tabular}{@{}ll@{}}
% \verb|sum{i in S diff T} alpha[i] * b[i,j]|&(iterated expression)\\
% \verb|if i in I then 2 * p else q[i+1]|&(conditional expression)\\
% \verb|(b[i,j] + .5 * c)|&(parenthesized expression)\\
% \end{tabular}
Expressões numéricas mais genéricas, contendo duas ou mais
expressões numéricas primárias, podem ser construídas usando
determinados operadores aritméticos.
% More general numeric expressions containing two or more primary numeric
% expressions may be constructed by using certain arithmetic operators.
\para{Exemplos}
\begin{verbatim}
j+1
2 * a[i-1,j+1] - b[i,j]
sum{j in J} a[i,j] * x[j] + sum{k in K} b[i,k] * x[k]
(if i in I and p >= 1 then 2 * p else q[i+1]) / (a[i,j] + 1.5)
\end{verbatim}
\subsection{Literais numéricos}
Se a expressão numérica primária é um literal numérico,
o valor resultante é óbvio.
% If the primary numeric expression is a numeric literal, the resultant
% value is obvious.
\subsection{Índices}
Se a expressão numérica primária é um índice,
o valor resultante é o valor corrente atribuído àquele índice.
% If the primary numeric expression is a dummy index, the resultant value
% is current value assigned to that dummy index.
\subsection{Parâmetros não-indexados}
Se a expressão numérica primária é um parâmetro não-indexado
(que deve ser 0-dimensional), o valor resultante é o valor
do parâmetro.
% If the primary numeric expression is an unsubscripted parameter (which
% should be 0-dimen\-sional), the resultant value is the value of that
% parameter.
\subsection{Parâmetros indexados}
A expressão numérica primária, que se refere ao parâmetro indexado,
possui a seguinte forma sintática:
% The primary numeric expression, which refers to a subscripted
% parameter, has the following syntactic form:
$$
\mbox{{\it nome}{\tt[}$i_1${\tt,} $i_2${\tt,} \dots{\tt,} $i_n${\tt]}}
$$
onde {\it nome} é o nome simbólico do parâmetro e $i_1$, $i_2$,
\dots, $i_n$ são subíndices.
Cada subíndice deve ser uma expressão numérica ou simbólica. O número
de subíndices na lista de subíndices deve ser o mesmo da dimensão
do parâmetro com o qual a lista de subíndices está associada.
Os valores reais das expressões de subíndice são usadas para identificar
um membro particular do parâmetro que determina o valor resultante
da expressão primária.
% where {\it name} is the symbolic name of the parameter, $i_1$, $i_2$,
% \dots, $i_n$ are subscripts.
%
% Each subscript should be a numeric or symbolic expression. The number
% of subscripts in the subscript list should be the same as the dimension
% of the parameter with which the subscript list is associated.
%
% Actual values of subscript expressions are used to identify
% a particular member of the parameter that determines the resultant
% value of the primary expression.
\newpage
\subsection{Funções de referência}
Em MathProg existem as seguintes funções internas, que podem ser
usadas como expressões numéricas:
% In MathProg there exist the following built-in functions which may be
% used in numeric expressions:
\begin{tabular}{@{}p{112pt}p{328pt}@{}}
{\tt abs(}$x${\tt)}&$|x|$, valor absoluto de $x$\\
{\tt atan(}$x${\tt)}&$\arctan x$, valor principal do arco tangente de
$x$ (em radianos)\\
{\tt atan(}$y${\tt,} $x${\tt)}&$\arctan y/x$, valor principal do
arco tangente de $y/x$ (em radianos). Neste caso, os sinais de ambos
argumentos $y$ e $x$ são usados para determinar o quadrante do valor
resultante\\
{\tt card(}$X${\tt)}&$|X|$, cardinalidade (o número de elementos) do
conjunto $X$\\
{\tt ceil(}$x${\tt)}&$\lceil x\rceil$, menor inteiro não menor que
$x$ (``teto de $x$'')\\
{\tt cos(}$x${\tt)}&$\cos x$, cosseno de $x$ (em radianos)\\
{\tt exp(}$x${\tt)}&$e^x$, exponencial de $x$ na base-$e$\\
{\tt floor(}$x${\tt)}&$\lfloor x\rfloor$, maior inteiro não maior
que $x$ (``piso de $x$'')\\
{\tt gmtime()}&o número de segundos decorridos deste 00:00:00 de~01~de~Jan de 1970,
Tempo Universal Coordenado (detalhes na Seção \ref{gmtime},
página \pageref{gmtime})\\
{\tt length(}$s${\tt)}&$|s|$, comprimento da cadeia de caracteres $s$\\
{\tt log(}$x${\tt)}&$\log x$, logaritmo natural de $x$\\
{\tt log10(}$x${\tt)}&$\log_{10}x$, logaritmo comum (decimal) de $x$\\
{\tt max(}$x_1${\tt,} $x_2${\tt,} \dots{\tt,} $x_n${\tt)}&o maior
dos valores $x_1$, $x_2$, \dots, $x_n$\\
{\tt min(}$x_1${\tt,} $x_2${\tt,} \dots{\tt,} $x_n${\tt)}&o menor
dos valores $x_1$, $x_2$, \dots, $x_n$\\
{\tt round(}$x${\tt)}&arrendondamento de $x$ ao inteiro mais próximo\\
{\tt round(}$x${\tt,} $n${\tt)}&arrendondamento de $x$ a $n$ dígitos decimais\\
{\tt sin(}$x${\tt)}&$\sin x$, seno de $x$ (em radianos)\\
{\tt sqrt(}$x${\tt)}&$\sqrt{x}$, raiz quadrada não-negativa de $x$\\
{\tt str2time(}$s${\tt,} $f${\tt)}&conversão de uma cadeia de caracteres $s$ ao
tempo calendário (detalhes na Seção \ref{str2time}, página
\pageref{str2time})\\
{\tt trunc(}$x${\tt)}&truncado de $x$ ao inteiro mais próximo\\
{\tt trunc(}$x${\tt,} $n${\tt)}&truncado de $x$ a $n$ dígitos decimais\\
{\tt Irand224()}&gera inteiro pseudo-aleatório uniformemente distribuído
em $[0,2^{24})$\\
{\tt Uniform01()}&gera número pseudo-aleatório uniformemente distribuído
em $[0,1)$\\
{\tt Uniform(}$a${\tt,} $b${\tt)}&gera número pseudo-aleatório uniformemente
distribuído em $[a,b)$\\
{\tt Normal01()}&gera variável Gaussiana pseudo-aleatória com
$\mu=0$ e $\sigma=1$\\
{\tt Normal(}$\mu${\tt,} $\sigma${\tt)}&gera variável Gaussiana pseudo-aleatória
com $\mu$ e $\sigma$ dados\\
\end{tabular}
% \begin{tabular}{@{}p{112pt}p{328pt}@{}}
% {\tt abs(}$x${\tt)}&$|x|$, absolute value of $x$\\
% {\tt atan(}$x${\tt)}&$\arctan x$, principal value of the arc tangent of
% $x$ (in radians)\\
% {\tt atan(}$y${\tt,} $x${\tt)}&$\arctan y/x$, principal value of the
% arc tangent of $y/x$ (in radians). In this case the signs of both
% arguments $y$ and $x$ are used to determine the quadrant of the
% resultant value\\
% {\tt card(}$X${\tt)}&$|X|$, cardinality (the number of elements) of
% set $X$\\
% {\tt ceil(}$x${\tt)}&$\lceil x\rceil$, smallest integer not less than
% $x$ (``ceiling of $x$'')\\
% {\tt cos(}$x${\tt)}&$\cos x$, cosine of $x$ (in radians)\\
% {\tt exp(}$x${\tt)}&$e^x$, base-$e$ exponential of $x$\\
% {\tt floor(}$x${\tt)}&$\lfloor x\rfloor$, largest integer not greater
% than $x$ (``floor of $x$'')\\
% {\tt gmtime()}&the number of seconds elapsed since 00:00:00~Jan~1, 1970,
% Coordinated Universal Time (for details see Section \ref{gmtime},
% page \pageref{gmtime})\\
% {\tt length(}$s${\tt)}&$|s|$, length of character string $s$\\
% {\tt log(}$x${\tt)}&$\log x$, natural logarithm of $x$\\
% {\tt log10(}$x${\tt)}&$\log_{10}x$, common (decimal) logarithm of $x$\\
% {\tt max(}$x_1${\tt,} $x_2${\tt,} \dots{\tt,} $x_n${\tt)}&the largest
% of values $x_1$, $x_2$, \dots, $x_n$\\
% {\tt min(}$x_1${\tt,} $x_2${\tt,} \dots{\tt,} $x_n${\tt)}&the smallest
% of values $x_1$, $x_2$, \dots, $x_n$\\
% {\tt round(}$x${\tt)}&rounding $x$ to nearest integer\\
% {\tt round(}$x${\tt,} $n${\tt)}&rounding $x$ to $n$ fractional decimal
% digits\\
% {\tt sin(}$x${\tt)}&$\sin x$, sine of $x$ (in radians)\\
% {\tt sqrt(}$x${\tt)}&$\sqrt{x}$, non-negative square root of $x$\\
% {\tt str2time(}$s${\tt,} $f${\tt)}&converting character string $s$ to
% calendar time (for details see Section \ref{str2time}, page
% \pageref{str2time})\\
% {\tt trunc(}$x${\tt)}&truncating $x$ to nearest integer\\
% {\tt trunc(}$x${\tt,} $n${\tt)}&truncating $x$ to $n$ fractional
% decimal digits\\
% {\tt Irand224()}&generating pseudo-random integer uniformly distributed
% in $[0,2^{24})$\\
% {\tt Uniform01()}&generating pseudo-random number uniformly distributed
% in $[0,1)$\\
% {\tt Uniform(}$a${\tt,} $b${\tt)}&generating pseudo-random number
% uniformly distributed in $[a,b)$\\
% {\tt Normal01()}&generating Gaussian pseudo-random variate with
% $\mu=0$ and $\sigma=1$\\
% {\tt Normal(}$\mu${\tt,} $\sigma${\tt)}&generating Gaussian
% pseudo-random variate with given $\mu$ and $\sigma$\\
% \end{tabular}
Os argumentos de todas as funções internas, exceto {\tt card}, {\tt length},
e {\tt str2time}, devem ser \linebreak expressões numéricas. O argumento de
{\tt card} deve ser uma expressão de conjunto. O argumento de {\tt length} e
ambos argumentos de {\tt str2time} devem ser expressões simbólicas.
O valor resultante da expressão numérica, que é uma função de referência,
é o resultado da aplicação da função ao(s) seu(s) argumento(s).
Note que cada função geradora de números pseudo-aleatórios possui um argumento
latente (i.e., algum estado interno), que é alterado sempre que função é aplicada.
Assim, se a função é aplicada repetidamente mesmos aos argumentos idênticos,
devido ao efeito secundário, sempre se produzirão valores resultantes diferentes.
% Arguments of all built-in functions, except {\tt card}, {\tt length},
% and {\tt str2time}, should be numeric expressions. The argument of
% {\tt card} should be a set expression. The argument of {\tt length} and
% both arguments of {\tt str2time} should be symbolic expressions.
%
% The resultant value of the numeric expression, which is a function
% reference, is the result of applying the function to its argument(s).
%
% Note that each pseudo-random generator function has a latent argument
% (i.e. some internal state), which is changed whenever the function has
% been applied. Thus, if the function is applied repeatedly even to
% identical arguments, due to the side effect different resultant values
% are always produced.
\newpage
\subsection{Expressões iteradas}
\label{itexpr}
Uma {\it expressão numérica iterada} é uma expressão numérica primária,
que possui a seguinte forma sintática:
$$\mbox{\it operador-iterado expressão-indexada integrando}$$
onde o {\it operador-iterado} é o nome simbólico do operador de iteração
a ser executado (veja abaixo), {\it expressão-indexada} é uma
expressão indexada que introduz índices e controla a iteração e
{\it integrando} é uma expressão numérica que participa da operação.
\noindent
Em MathProg existem quatro operadores iterados, que podem ser usados
em expressões numéricas:
% An {\it iterated numeric expression} is a primary numeric expression,
% which has the following syntactic form:
% $$\mbox{\it iterated-operator indexing-expression integrand}$$
% where {\it iterated-operator} is the symbolic name of the iterated
% operator to be performed (see below), {\it indexing-expression} is an
% indexing expression which introduces dummy indices and controls
% iterating, {\it integrand} is a numeric expression that participates in
% the operation.
%
% In MathProg there exist four iterated operators, which may be used in
% numeric expressions:
{\def\arraystretch{2}
\noindent\hfil
\begin{tabular}{@{}lll@{}}
{\tt sum}&somatório&$\displaystyle\sum_{(i_1,\dots,i_n)\in\Delta}
f(i_1,\dots,i_n)$\\
{\tt prod}&produtório&$\displaystyle\prod_{(i_1,\dots,i_n)\in\Delta}
f(i_1,\dots,i_n)$\\
{\tt min}&mínimo&$\displaystyle\min_{(i_1,\dots,i_n)\in\Delta}
f(i_1,\dots,i_n)$\\
{\tt max}&máximo&$\displaystyle\max_{(i_1,\dots,i_n)\in\Delta}
f(i_1,\dots,i_n)$\\
\end{tabular}
}
% {\def\arraystretch{2}
% \noindent\hfil
% \begin{tabular}{@{}lll@{}}
% {\tt sum}&summation&$\displaystyle\sum_{(i_1,\dots,i_n)\in\Delta}
% f(i_1,\dots,i_n)$\\
% {\tt prod}&production&$\displaystyle\prod_{(i_1,\dots,i_n)\in\Delta}
% f(i_1,\dots,i_n)$\\
% {\tt min}&minimum&$\displaystyle\min_{(i_1,\dots,i_n)\in\Delta}
% f(i_1,\dots,i_n)$\\
% {\tt max}&maximum&$\displaystyle\max_{(i_1,\dots,i_n)\in\Delta}
% f(i_1,\dots,i_n)$\\
% \end{tabular}
% }
\noindent onde $i_1$, \dots, $i_n$ são índices introduzidos nas
expressões indexadas, $\Delta$ é o domínio, um conjunto de $n$-tuplas
especificado pela expressão indexada que define valores particulares
atribuído aos índices ao executar a operação iterada e
$f(i_1,\dots,i_n)$ é o integrando, uma expressão numérica cujo valor
resultante depende dos índices.
O valor resultante de uma expressão numérica iterada é o resultado da aplicação
do operador iterado ao seu integrando por todas as $n$-tuplas
contidas no domínio.
% \noindent where $i_1$, \dots, $i_n$ are dummy indices introduced in
% the indexing expression, $\Delta$ is the domain, a set of $n$-tuples
% specified by the indexing expression which defines particular values
% assigned to the dummy indices on performing the iterated operation,
% $f(i_1,\dots,i_n)$ is the integrand, a numeric expression whose
% resultant value depends on the dummy indices.
%
% The resultant value of an iterated numeric expression is the result of
% applying of the iterated operator to its integrand over all $n$-tuples
% contained in the domain.
\subsection{Expressões condicionais}
\label{ifthen}
Uma {\it expressão numérica condicional} é uma expressão numérica primária
que possui uma das seguintes formas sintáticas:
% A {\it conditional numeric expression} is a primary numeric expression,
% which has one of the following two syntactic forms:
$$
{\def\arraystretch{1.4}
\begin{array}{l}
\mbox{{\tt if} $b$ {\tt then} $x$ {\tt else} $y$}\\
\mbox{{\tt if} $b$ {\tt then} $x$}\\
\end{array}
}
$$
onde $b$ é uma expressão lógica, enquanto que $x$ e $y$ são expressões numéricas.
% where $b$ is an logical expression, $x$ and $y$ are numeric
% expressions.
O valor resultante da expressão condicional depende do valor da
expressão lógica que segue a palavra-chave {\tt if}. Se ela recebe
o valor {\it verdadeiro}, o valor da expressão condicional é o valor
da expressão que segue a palavra-chave {\tt then}.
Caso contrário, se a expressão lógica recebe o valor {\it falso},
o valor da expressão condicional é o valor da expressão que segue
a palavra-chave {\it else}. Se ocorre a segunda forma sintática
da expressão condicional, a reduzida, e a expressão lógica recebe o valor
{\it falso}, então o valor resultante da expressão condicional é zero.
% The resultant value of the conditional expression depends on the value
% of the logical expression that follows the keyword {\tt if}. If it
% takes on the value {\it true}, the value of the conditional expression
% is the value of the expression that follows the keyword {\tt then}.
% Otherwise, if the logical expression takes on the value {\it false},
% the value of the conditional expression is the value of the expression
% that follows the keyword {\it else}. If the second, reduced form of the
% conditional expression is used and the logical expression takes on the
% value {\it false}, the resultant value of the conditional expression is
% zero.
\newpage
\subsection{Expressões parentizadas}
Qualquer expressão numérica pode ser cercada por parênteses, o que as
torna sintaticamente uma expressão numérica primária.
Parênteses podem ser usados em expressões numéricas, como em álgebra, para
especificar a ordem desejada na qual as operações devem ser realizadas.
Quando se usam parênteses, a expressão entre parênteses é avaliada
antes e seu o valor resultante é usado.
O valor resultante de uma expressão parentizada é o mesmo
valor de uma expressão cercada entre parênteses.
% Any numeric expression may be enclosed in parentheses that
% syntactically makes it a primary numeric expression.
%
% Parentheses may be used in numeric expressions, as in algebra, to
% specify the desired order in which operations are to be performed.
% Where parentheses are used, the expression within the parentheses is
% evaluated before the resultant value is used.
%
% The resultant value of the parenthesized expression is the same as the
% value of the expression enclosed within parentheses.
\subsection{Operadores aritméticos}
Em MathProg exitem os seguintes operadores aritméticos, que podem ser
usados em expressões numéricas:
% In MathProg there exist the following arithmetic operators, which may
% be used in numeric expressions:
\begin{tabular}{@{}ll@{}}
{\tt +} $x$&mais unário\\
{\tt -} $x$&menos unário\\
$x$ {\tt +} $y$&adição\\
$x$ {\tt -} $y$&subtração\\
$x$ {\tt less} $y$&diferença positiva (se $x<y$ então 0 senão $x-y$)\\
$x$ {\tt *} $y$&multiplicação\\
$x$ {\tt /} $y$&divisão\\
$x$ {\tt div} $y$&quociente da divisão exata\\
$x$ {\tt mod} $y$&resto da divisão exata\\
$x$ {\tt **} $y$, $x$ {\tt\textasciicircum} $y$&exponenciação (elevação a uma potência)\\
\end{tabular}
% \begin{tabular}{@{}ll@{}}
% {\tt +} $x$&unary plus\\
% {\tt -} $x$&unary minus\\
% $x$ {\tt +} $y$&addition\\
% $x$ {\tt -} $y$&subtraction\\
% $x$ {\tt less} $y$&positive difference (if $x<y$ then 0 else $x-y$)\\
% $x$ {\tt *} $y$&multiplication\\
% $x$ {\tt /} $y$&division\\
% $x$ {\tt div} $y$"ient of exact division\\
% $x$ {\tt mod} $y$&remainder of exact division\\
% $x$ {\tt **} $y$, $x$ {\tt\textasciicircum} $y$&exponentiation (raising
% to power)\\
% \end{tabular}
\noindent onde $x$ e $y$ são expressões numéricas.
Se a expressão inclui mais de um operador aritmético, todos
operadores são executados da esquerda para a direita de acordo
com a hierarquia das operações (veja abaixo) com a única exceção de
que os operadores de exponenciação são executados da direita para a esquerda.
O valor resultante da expressão, que contém operadores aritméticos,
é o resultado da aplicação dos operadores aos seus operandos.
% \noindent where $x$ and $y$ are numeric expressions.
%
% If the expression includes more than one arithmetic operator, all
% operators are performed from left to right according to the hierarchy
% of operations (see below) with the only exception that the
% exponentiaion operators are performed from right to left.
%
% The resultant value of the expression, which contains arithmetic
% operators, is the result of applying the operators to their operands.
\subsection{Hierarquia das operações}
\label{hierarchy}
A lista seguinte apresenta a hierarquia das operações
em expressões numéricas:
% The following list shows the hierarchy of operations in numeric
% expressions:
\noindent\hfil
\begin{tabular}{@{}ll@{}}
Operação&Hierarquia\\
\hline
Avaliação das funções ({\tt abs}, {\tt ceil}, etc.)&
1{\textsuperscript{\b{a}}}\\
Exponenciação ({\tt**}, {\tt\textasciicircum})&
2{\textsuperscript{\b{a}}}\\
Mais e menos unário ({\tt+}, {\tt-})&
3{\textsuperscript{\b{a}}}\\
Multiplicação e divisão ({\tt*}, {\tt/}, {\tt div}, {\tt mod})&
4{\textsuperscript{\b{a}}}\\
Operações iteradas ({\tt sum}, {\tt prod}, {\tt min}, {\tt max})&
5{\textsuperscript{\b{a}}}\\
Adição e subtração ({\tt+}, {\tt-}, {\tt less})&
6{\textsuperscript{\b{a}}}\\
Avaliação condicional ({\tt if} \dots {\tt then} \dots {\tt else})&
7{\textsuperscript{\b{a}}}\\
\end{tabular}
% \noindent\hfil
% \begin{tabular}{@{}ll@{}}
% Operation&Hierarchy\\
% \hline
% Evaluation of functions ({\tt abs}, {\tt ceil}, etc.)&1st\\
% Exponentiation ({\tt**}, {\tt\textasciicircum})&2nd\\
% Unary plus and minus ({\tt+}, {\tt-})&3rd\\
% Multiplication and division ({\tt*}, {\tt/}, {\tt div}, {\tt mod})&4th\\
% Iterated operations ({\tt sum}, {\tt prod}, {\tt min}, {\tt max})&5th\\
% Addition and subtraction ({\tt+}, {\tt-}, {\tt less})&6th\\
% Conditional evaluation ({\tt if} \dots {\tt then} \dots {\tt else})&
% 7th\\
% \end{tabular}
\newpage
Esta hierarquia é usada para determinar qual de duas operações consecutivas
deve ser executada primeiro. Se o primeiro operador possui hierarquia
maior ou igual ao segundo, a primeira operação é executada. Caso contrário,
a segunda operação é comparada à terceira e assim sucessivamente.
Quando se alcança o fim da expressão, todas as operações remanescentes
são executadas na ordem inversa.
% This hierarchy is used to determine which of two consecutive operations
% is performed first. If the first operator is higher than or equal to
% the second, the first operation is performed. If it is not, the second
% operator is compared to the third, etc. When the end of the expression
% is reached, all of the remaining operations are performed in the
% reverse order.
\section{Expressões simbólicas}
Uma {\it expressão simbólica} é uma regra para calcular um valor simbólico individual
representado como uma cadeia de caracteres.
A expressão simbólica primária pode ser uma cadeia literal, um índice,
um parâmetro não-indexado, um parâmetro indexado, uma função interna de referência,
uma expressão simbólica condicional ou outra expressão simbólica cercada
entre parênteses.
Também é permitido usar uma expressão numérica como a expressão simbólica primária,
neste caso o valor resultante da expressão numérica é automaticamente convertido
em um tipo simbólico.
% A {\it symbolic expression} is a rule for computing a single symbolic
% value represented as a character string.
%
% The primary symbolic expression may be a string literal, dummy index,
% unsubscripted parameter, subscripted parameter, built-in function
% reference, conditional symbolic expression, or another symbolic
% expression enclosed in parentheses.
%
% It is also allowed to use a numeric expression as the primary symbolic
% expression, in which case the resultant value of the numeric expression
% is automatically converted to the symbolic type.
\para{Exemplos}
\noindent
\begin{tabular}{@{}ll@{}}
\verb|'Maio de 2003'|&(literal de cadeia)\\
\verb|j|&(índice)\\
\verb|p|&(parâmetro não-indexado)\\
\verb|s['abc',j+1]|&(parâmetro indexado)\\
\verb|substr(name[i],k+1,3)|&(função de referência)\\
\verb|if i in I then s[i,j] & "..." else t[i+1]|& (expressão condicional) \\
\verb|((10 * b[i,j]) & '.bis')|&(expressão parentizada)\\
\end{tabular}
% \noindent
% \begin{tabular}{@{}ll@{}}
% \verb|'May 2003'|&(string literal)\\
% \verb|j|&(dummy index)\\
% \verb|p|&(unsubscripted parameter)\\
% \verb|s['abc',j+1]|&(subscripted parameter)\\
% \verb|substr(name[i],k+1,3)|&(function reference)\\
% \verb|if i in I then s[i,j] & "..." else t[i+1]|
% & (conditional expression) \\
% \verb|((10 * b[i,j]) & '.bis')|&(parenthesized expression)\\
% \end{tabular}
Expressões simbólicas mais genéricas contendo duas ou mais expressões
simbólicas primárias podem ser construídas usando o operador de
concatenação.
% More general symbolic expressions containing two or more primary
% symbolic expressions may be constructed by using the concatenation
% operator.
\para{Exemplos}
\begin{verbatim}
'abc[' & i & ',' & j & ']'
"de " & cidade[i] " para " & cidade[j]
\end{verbatim}
% \begin{verbatim}
% 'abc[' & i & ',' & j & ']'
% "from " & city[i] " to " & city[j]
% \end{verbatim}
Os princípios da avaliação de expressões simbólicas são completamente
análogos àqueles dados para expressões numéricas (veja acima).
% The principles of evaluation of symbolic expressions are completely
% analogous to the ones given for numeric expressions (see above).
\subsection{Funções de referência}
Em MathProg existem as seguintes funções internas que podem ser usadas em
expressões \linebreak simbólicas:
% In MathProg there exist the following built-in functions which may be
% used in symbolic expressions:
\begin{tabular}{@{}p{112pt}p{328pt}@{}}
{\tt substr(}$s${\tt,} $x${\tt)}&substring de $s$ iniciado na
posição $x$\\
{\tt substr(}$s${\tt,} $x${\tt,} $y${\tt)}&substring de $s$ iniciado
na posição $x$ com tamanho $y$\\
{\tt time2str(}$t${\tt,} $f${\tt)}&converte o tempo de calendário para
uma cadeia de caracteres \linebreak (detalhes na Seção \ref{time2str}, página
\pageref{time2str})\\
\end{tabular}
% \begin{tabular}{@{}p{112pt}p{328pt}@{}}
% {\tt substr(}$s${\tt,} $x${\tt)}&substring of $s$ starting from
% position $x$\\
% {\tt substr(}$s${\tt,} $x${\tt,} $y${\tt)}&substring of $s$ starting
% from position $x$ and having length $y$\\
% {\tt time2str(}$t${\tt,} $f${\tt)}&converting calendar time to
% character string (for details see Section \ref{time2str}, page
% \pageref{time2str})\\
% \end{tabular}
O primeiro argumento de {\tt substr} deve ser uma expressão simbólica
enquanto que o segundo e o terceiro (opcional) argumentos devem ser
expressões numéricas.
O primeiro argumento de {\tt time2str} deve ser uma expressão numérica,
e seu segundo argumento deve ser uma expressão simbólica.
O valor resultante da expressão simbólica, que é uma função de referência,
é o resultado de aplicar a função aos seus argumentos.
% The first argument of {\tt substr} should be a symbolic expression
% while its second and optional third arguments should be numeric
% expressions.
%
% The first argument of {\tt time2str} should be a numeric expression,
% and its second argument should be a symbolic expression.
%
% The resultant value of the symbolic expression, which is a function
% reference, is the result of applying the function to its arguments.
\subsection{Operadores simbólicos}
Atualmente, em MathProg exite um único operador simbólico:
$$\mbox{\tt s \& t}$$
onde $s$ e $t$ são expressões simbólicas. Este operador implica na
concatenação dos seus dois operandos simbólicos, que são cadeias
de caracteres.
% Currently in MathProg there exists the only symbolic operator:
% $$\mbox{\tt s \& t}$$
% where $s$ and $t$ are symbolic expressions. This operator means
% concatenation of its two symbolic operands, which are character
% strings.
\subsection{Hierarquia de operações}
A lista seguinte mostra a hierarquia das operações em expressões
simbólicas:
% The following list shows the hierarchy of operations in symbolic
% expressions:
\noindent\hfil
\begin{tabular}{@{}ll@{}}
Operação&Hierarquia\\
\hline
Avaliação de operações numéricas&
1{\textsuperscript{\b{a}}}-7{\textsuperscript{\b{a}}}\\
Concatenação ({\tt\&})&8{\textsuperscript{\b{a}}}\\
Avaliação condicional ({\tt if} \dots {\tt then} \dots {\tt else})&
9{\textsuperscript{\b{a}}}\\
\end{tabular}
% \noindent\hfil
% \begin{tabular}{@{}ll@{}}
% Operation&Hierarchy\\
% \hline
% Evaluation of numeric operations&1st-7th\\
% Concatenation ({\tt\&})&8th\\
% Conditional evaluation ({\tt if} \dots {\tt then} \dots {\tt else})&
% 9th\\
% \end{tabular}
Esta hierarquia possui o mesmo significado como explicado acima para
expressões numéricas (ver Subseção \ref{hierarchy}, página \pageref{hierarchy}).
% This hierarchy has the same meaning as was explained above for numeric
% expressions (see Subsection \ref{hierarchy}, page \pageref{hierarchy}).
\section{Expressões de indexação e índices}
\label{indexing}
Uma {\it expressão indexante} é uma construção auxiliar que especifica um
conjunto plano de $n$-tuplas e introduz índices. Possui duas formas
sintáticas:
% An {\it indexing expression} is an auxiliary construction, which
% specifies a plain set of $n$-tuples and introduces dummy indices. It
% has two syntactic forms:
$$
{\def\arraystretch{1.4}
\begin{array}{l}
\mbox{{\tt\{} {\it entrada}$_1${\tt,} {\it entrada}$_2${\tt,} \dots{\tt,}
{\it entrada}$_m$ {\tt\}}}\\
\mbox{{\tt\{} {\it entrada}$_1${\tt,} {\it entrada}$_2${\tt,} \dots{\tt,}
{\it entrada}$_m$ {\tt:} {\it predicado} {\tt\}}}\\
\end{array}
}
$$
% $$
% {\def\arraystretch{1.4}
% \begin{array}{l}
% \mbox{{\tt\{} {\it entry}$_1${\tt,} {\it entry}$_2${\tt,} \dots{\tt,}
% {\it entry}$_m$ {\tt\}}}\\
% \mbox{{\tt\{} {\it entry}$_1${\tt,} {\it entry}$_2${\tt,} \dots{\tt,}
% {\it entry}$_m$ {\tt:} {\it predicate} {\tt\}}}\\
% \end{array}
% }
% $$
onde {\it entrada}{$_1$}, {\it entrada}{$_2$}, \dots, {\it entrada}{$_m$}
são entradas indexantes, {\it predicado} é uma expressão lógica que especifica
um predicado opcional (condição lógica).
% where {\it entry}{$_1$}, {\it entry}{$_2$}, \dots, {\it entry}{$_m$}
% are indexing entries, {\it predicate} is a logical expression that
% specifies an optional predicate (logical condition).
Cada {\it entrada indexante} na expressão indexante possui uma das três
formas seguintes:
% Each {\it indexing entry} in the indexing expression has one of the
% following three forms:
$$
{\def\arraystretch{1.4}
\begin{array}{l}
\mbox{$i$ {\tt in} $S$}\\
\mbox{{\tt(}$i_1${\tt,} $i_2${\tt,} \dots{\tt,}$i_n${\tt)} {\tt in}
$S$}\\
\mbox{$S$}\\
\end{array}
}
$$
onde $i_1$, $i_2$, \dots, $i_n$ são índices e $S$ é uma expressão de conjunto
(discutido na próxima seção) que especifica o conjunto básico.
% where $i_1$, $i_2$, \dots, $i_n$ are indices, $S$ is a set expression
% (discussed in the next section) that specifies the basic set.
\newpage
O número de índices na entrada indexante deve coincidir com a
dimensão do conjunto básico $S$, i.e., se $S$ consiste de 1-tuplas,
deve-se usar a primeira forma. Se $S$ consiste de $n$-tuplas, onde
$n>1$, a segunda forma deve ser usada.
% The number of indices in the indexing entry should be the same as the
% dimension of the basic set $S$, i.e. if $S$ consists of 1-tuples, the
% first form should be used, and if $S$ consists of $n$-tuples, where
% $n>1$, the second form should be used.
Se a primeira forma da entrada indexante é usada, o índice $i$ pode ser
apenas um índice (veja mais adiante). Se a segunda forma é utilizada, os índices
$i_1$, $i_2$, \dots, $i_n$ podem ser tanto índices como alguma expressão numérica
ou simbólica, em que pelo menos um dos índices deve ser um índice.
Na terceira, a forma reduzida da entrada indexante possui o mesmo efeito
se houver $i$ (se $S$ é 1-dimensional) ou
$i_1$, $i_2$, \dots, $i_n$ (se $S$ é $n$-dimensional) onde todos são especificados
como índices.
% If the first form of the indexing entry is used, the index $i$ can be
% a dummy index only (see below). If the second form is used, the indices
% $i_1$, $i_2$, \dots, $i_n$ can be either dummy indices or some numeric
% or symbolic expressions, where at least one index should be a dummy
% index. The third, reduced form of the indexing entry has the same
% effect as if there were $i$ (if $S$ is 1-dimensional) or
% $i_1$, $i_2$, \dots, $i_n$ (if $S$ is $n$-dimensional) all specified as
% dummy indices.
Um {\it índice} é um objeto auxiliar do modelo, que atua como uma
variável individual. Os valores atribuídos aos índices são componentes
das $n$-tuplas dos conjuntos básicos, i.e., algumas quantidades
numéricas e simbólicas.
% A {\it dummy index} is an auxiliary model object, which acts like an
% individual variable. Values assigned to dummy indices are components of
% $n$-tuples from basic sets, i.e. some numeric and symbolic quantities.
Com propósitos de referência, índices podem ter nomes simbólicos.
No entanto, diferentemente de outros objetos de modelo (conjuntos,
parâmetros, etc.) índices não precisam ser \linebreak explicitamente declarados.
Cada nome simbólico {\it não-declarado} usado na posição indexante de
uma entrada indexante é reconhecida como o nome simbólico do índice
correspondente.
% For referencing purposes dummy indices can be provided with symbolic
% names. However, unlike other model objects (sets, parameters, etc.)
% dummy indices need not be explicitly declared. Each {\it undeclared}
% symbolic name being used in the indexing position of an indexing entry
% is recognized as the symbolic name of corresponding dummy index.
Os nomes simbólicos dos índices são válidos somente dentro do escopo
da expressão indexante, onde o índice foi inserido. Além do escopo,
os índices são completamente inacessíveis, de modo que os mesmos
nomes simbólicos podem ser usados para outros propósitos, em particular,
para representar índices em outras expressões indexantes.
% Symbolic names of dummy indices are valid only within the scope of the
% indexing expression, where the dummy indices were introduced. Beyond
% the scope the dummy indices are completely inaccessible, so the same
% symbolic names may be used for other purposes, in particular, to
% represent dummy indices in other indexing expressions.
O escopo da expressão indexante, em que declarações implícitas de índices
são válidas, depende do contexto em que a expressão indexante é usada:
% The scope of indexing expression, where implicit declarations of dummy
% indices are valid, depends on the context, in which the indexing
% expression is used:
\vspace*{-8pt}
\begin{itemize}
\item Se a expressão indexante é usada em um operador-iterado, seu
escopo se estende até o final do integrando.
\item Se a expressão indexante é usada como uma expressão de conjunto
primária, seu escopo de estende até o final desta expressão indexante.
\item Se a expressão indexante é usada para definir o domínio do subíndice
na declaração de alguns objetos de modelo, seu escopo se estende até o
final da declaração correspondente.
\end{itemize}
% \begin{itemize}
% \item If the indexing expression is used in iterated operator, its
% scope extends until the end of the integrand.
% \item If the indexing expression is used as a primary set expression,
% its scope extends until the end of that indexing expression.
% \item If the indexing expression is used to define the subscript domain
% in declarations of some model objects, its scope extends until the end
% of the corresponding statement.
% \end{itemize}
\vspace*{-8pt}
O mecanismo de indexação implementado para indexar expressões é melhor
explicado por alguns exemplos discutidos abaixo.
Sejam três conjuntos:
% The indexing mechanism implemented by means of indexing expressions is
% best explained by some examples discussed below.
%
% Let there be given three sets:
$$
{\def\arraystretch{1.4}
\begin{array}{l}
A=\{4,7,9\},\\
B=\{(1,Jan),(1,Fev),(2,Mar),(2,Abr),(3,Mai),(3,Jun)\},\\
C=\{a,b,c\},\\
\end{array}
}
$$
% $$
% {\def\arraystretch{1.4}
% \begin{array}{l}
% A=\{4,7,9\},\\
% B=\{(1,Jan),(1,Feb),(2,Mar),(2,Apr),(3,May),(3,Jun)\},\\
% C=\{a,b,c\},\\
% \end{array}
% }
% $$
onde $A$ e $C$ consistem de 1-tuplas (singletos), $B$ consiste de
2-tuplas (dobletes). Considere a seguinte expressão indexante:
$$\mbox{{\tt\{i in A, (j,k) in B, l in C\}}}$$
onde {\tt i}, {\tt j}, {\tt k}, e {\tt l} são índices.
% where $A$ and $C$ consist of 1-tuples (singlets), $B$ consists of
% 2-tuples (doublets). Consider the following indexing expression:
% $$\mbox{{\tt\{i in A, (j,k) in B, l in C\}}}$$
% where {\tt i}, {\tt j}, {\tt k}, and {\tt l} are dummy indices.
\newpage
Embora MathProg não seja uma linguagem procedural, para qualquer
expressão indexante uma descrição algorítmica equivalente pode ser dada.
Em particular, a descrição algorítmica da expressão indexante acima
poderia ser vista como segue:
% Although MathProg is not a procedural language, for any indexing
% expression an equivalent algorithmic description can be given. In
% particular, the algorithmic description of the indexing expression
% above could look like follows:
\noindent\hfil
\begin{tabular}{@{}l@{}}
{\bf para todo} $i\in A$ {\bf faça}\\
\hspace{16pt}{\bf para todo} $(j,k)\in B$ {\bf faça}\\
\hspace{32pt}{\bf para todo} $l\in C$ {\bf faça}\\
\hspace{48pt}{\it ação};\\
\end{tabular}
% \noindent\hfil
% \begin{tabular}{@{}l@{}}
% {\bf for all} $i\in A$ {\bf do}\\
% \hspace{16pt}{\bf for all} $(j,k)\in B$ {\bf do}\\
% \hspace{32pt}{\bf for all} $l\in C$ {\bf do}\\
% \hspace{48pt}{\it action};\\
% \end{tabular}
\noindent onde os índices $i$, $j$, $k$, $l$ são consecutivamente
atribuídos aos componentes correspondentes das $n$-tuplas dos conjuntos
básicos $A$, $B$, $C$, e {\it ação} é alguma ação que dependa do contexto
no qual a expressão indexante é usada. Por exemplo, se a ação fosse
imprimir os valores atuais dos índices, a impressão seria vista como segue:
% \noindent where the dummy indices $i$, $j$, $k$, $l$ are consecutively
% assigned corresponding components of $n$-tuples from the basic sets $A$,
% $B$, $C$, and {\it action} is some action that depends on the context,
% where the indexing expression is used. For example, if the action were
% printing current values of dummy indices, the printout would look like
% follows:
\noindent\hfil
\begin{tabular}{@{}llll@{}}
$i=4$&$j=1$&$k=Jan$&$l=a$\\
$i=4$&$j=1$&$k=Jan$&$l=b$\\
$i=4$&$j=1$&$k=Jan$&$l=c$\\
$i=4$&$j=1$&$k=Fev$&$l=a$\\
$i=4$&$j=1$&$k=Fev$&$l=b$\\
\multicolumn{4}{c}{.\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .}\\
$i=9$&$j=3$&$k=Jun$&$l=b$\\
$i=9$&$j=3$&$k=Jun$&$l=c$\\
\end{tabular}
% \noindent\hfil
% \begin{tabular}{@{}llll@{}}
% $i=4$&$j=1$&$k=Jan$&$l=a$\\
% $i=4$&$j=1$&$k=Jan$&$l=b$\\
% $i=4$&$j=1$&$k=Jan$&$l=c$\\
% $i=4$&$j=1$&$k=Feb$&$l=a$\\
% $i=4$&$j=1$&$k=Feb$&$l=b$\\
% \multicolumn{4}{c}{.\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .}\\
% $i=9$&$j=3$&$k=Jun$&$l=b$\\
% $i=9$&$j=3$&$k=Jun$&$l=c$\\
% \end{tabular}
Seja o exemplo da expressão indexante usado na seguinte
operação iterada:
$$\mbox{{\tt sum\{i in A, (j,k) in B, l in C\} p[i,j,k,l]}}$$
onde {\tt p} é uma parâmetro numérico 4-dimensional ou alguma
expressão numérica cujo valor resultante dependa de
{\tt i}, {\tt j}, {\tt k} e {\tt l}. Neste caso, a ação é o somatório,
de forma que o valor resultante da expressão numérica primária é:
$$\sum_{i\in A,(j,k)\in B,l\in C}(p_{ijkl}).$$
% Let the example indexing expression be used in the following iterated
% operation:
% $$\mbox{{\tt sum\{i in A, (j,k) in B, l in C\} p[i,j,k,l]}}$$
% where {\tt p} is a 4-dimensional numeric parameter or some numeric
% expression whose resultant value depends on {\tt i}, {\tt j}, {\tt k},
% and {\tt l}. In this case the action is summation, so the resultant
% value of the primary numeric expression is:
% $$\sum_{i\in A,(j,k)\in B,l\in C}(p_{ijkl}).$$
Agora seja a expressão indexante do exemplo usada como uma expressão
de conjunto primária. Neste caso, a ação é reunir todas as 4-tuplas
(quádruplas) da forma $(i,j,k,l)$ em um conjunto, de forma que o
valor resultante de tal operação é simplesmente o produto
Cartesiano dos conjuntos básicos:
$$A\times B\times C=\{(i,j,k,l):i\in A,(j,k)\in B,l\in C\}.$$
Note que neste caso, a mesma expressão indexante pode ser escrita
na forma reduzida:
$$\mbox{{\tt\{A, B, C\}}}$$
pois os índices $i$, $j$, $k$ e $l$ não são referenciados, portanto,
seus nomes simbólicos não precisam ser especificados.
% Now let the example indexing expression be used as a primary set
% expression. In this case the action is gathering all 4-tuples
% (quadruplets) of the form $(i,j,k,l)$ in one set, so the resultant
% value of such operation is simply the Cartesian product of the basic
% sets:
% $$A\times B\times C=\{(i,j,k,l):i\in A,(j,k)\in B,l\in C\}.$$
% Note that in this case the same indexing expression might be written in
% the reduced form:
% $$\mbox{{\tt\{A, B, C\}}}$$
% because the dummy indices $i$, $j$, $k$, and $l$ are not referenced and
% therefore their symbolic names need not be specified.
\newpage
Finalmente, seja a expressão indexante do exemplo usada como o domínio do
subíndice na declaração de um objeto de modelo 4-dimensional, por exemplo,
um parâmetro numérico:
% Finally, let the example indexing expression be used as the subscript
% domain in the declaration of a 4-dimensional model object, say,
% a numeric parameter:
$$\mbox{{\tt param p\{i in A, (j,k) in B, l in C\}} \dots {\tt;}}$$
\noindent Neste caso, a ação é gerar os membros do parâmetro,
onde cada membro possui a forma $p[i,j,k,l]$.
% \noindent In this case the action is generating the parameter members,
% where each member has the form $p[i,j,k,l]$.
Como mencionado anteriormente, alguns índices da segunda forma das entradas
indexantes podem ser expressões numéricas ou simbólicas, não apenas índices.
Neste caso, os valores resultantes destas expressões desempenham o papel
de algumas condições lógicas para selecionar apenas aquelas $n$-tuplas
do produto Cartesiano dos conjuntos básicos que satisfaçam estas
condições.
% As was said above, some indices in the second form of indexing entries
% may be numeric or symbolic expressions, not only dummy indices. In this
% case resultant values of such expressions play role of some logical
% conditions to select only that $n$-tuples from the Cartesian product of
% basic sets that satisfy these conditions.
Considere, por exemplo, a seguinte expressão indexante:
$$\mbox{{\tt\{i in A, (i-1,k) in B, l in C\}}}$$
onde {\tt i}, {\tt k} e {\tt l} são índices, e {\tt i-1} é uma
expressão numérica. A descrição algorítmica desta expressão
indexante é a seguinte:
% Consider, for example, the following indexing expression:
% $$\mbox{{\tt\{i in A, (i-1,k) in B, l in C\}}}$$
% where {\tt i}, {\tt k}, {\tt l} are dummy indices, and {\tt i-1} is
% a numeric expression. The algorithmic decsription of this indexing
% expression is the following:
\noindent\hfil
\begin{tabular}{@{}l@{}}
{\bf para todo} $i\in A$ {\bf faça}\\
\hspace{16pt}{\bf para todo} $(j,k)\in B$ {\bf e} $j=i-1$ {\bf faça}\\
\hspace{32pt}{\bf para todo} $l\in C$ {\bf faça}\\
\hspace{48pt}{\it ação};\\
\end{tabular}
% \noindent\hfil
% \begin{tabular}{@{}l@{}}
% {\bf for all} $i\in A$ {\bf do}\\
% \hspace{16pt}{\bf for all} $(j,k)\in B$ {\bf and} $j=i-1$ {\bf do}\\
% \hspace{32pt}{\bf for all} $l\in C$ {\bf do}\\
% \hspace{48pt}{\it action};\\
% \end{tabular}
\noindent Assim, se esta expressão indexante fosse usada como uma expressão de conjunto
primária, o conjunto resultante seira o seguinte:
$$\{(4,Mai,a),(4,Mai,b),(4,Mai,c),(4,Jun,a),(4,Jun,b),(4,Jun,c)\}.$$
Deve-se notar que neste caso o conjunto resultante consiste em 3-tuplas,
e não de 4-tuplas, porque na expressão indexante não há índice que
corresponda ao primeiro componente das 2-tuplas do conjunto $B$.
% \noindent Thus, if this indexing expression were used as a primary set
% expression, the resultant set would be the following:
% $$\{(4,May,a),(4,May,b),(4,May,c),(4,Jun,a),(4,Jun,b),(4,Jun,c)\}.$$
% Should note that in this case the resultant set consists of 3-tuples,
% not of 4-tuples, because in the indexing expression there is no dummy
% index that corresponds to the first component of 2-tuples from the set
% $B$.
A regra geral é: o número de componentes de $n$-tuplas definido por
uma expressão indexante é o mesmo do número de índices naquela expressão,
onde a correspondência entre índices e componentes nas $n$-tuplas no
conjunto resultante é posicional, i.e., o primeiro índice corresponde
ao primeiro componente, o segundo índice corresponde ao segundo
componente, etc.
% The general rule is: the number of components of $n$-tuples defined by
% an indexing expression is the same as the number of dummy indices in
% that expression, where the correspondence between dummy indices and
% components on $n$-tuples in the resultant set is positional, i.e. the
% first dummy index corresponds to the first component, the second dummy
% index corresponds to the second component, etc.
Em alguns casos é necessário selecionar um subconjunto do produto
Cartesiano de alguns \linebreak conjuntos. Isto pode ser alcançado mediante o
emprego de um predicado lógico opcional, que é especificado na
expressão indexante.
% In some cases it is needed to select a subset from the Cartesian
% product of some sets. This may be attained by using an optional logical
% predicate, which is specified in the indexing expression.
Considere, por exemplo, a seguinte expressão indexante:
$$\mbox{{\tt\{i in A, (j,k) in B, l in C: i <= 5 and k <> 'Mar'\}}}$$
onde a expressão lógica após os dois pontos é um predicado. A
descrição algorítmica desta expressão indexante é a seguinte:
% Consider, for example, the following indexing expression:
% $$\mbox{{\tt\{i in A, (j,k) in B, l in C: i <= 5 and k <> 'Mar'\}}}$$
% where the logical expression following the colon is a predicate. The
% algorithmic description of this indexing expression is the following:
\noindent\hfil
\begin{tabular}{@{}l@{}}
{\bf para todo} $i\in A$ {\bf faça}\\
\hspace{16pt}{\bf para todo} $(j,k)\in B$ {\bf faça}\\
\hspace{32pt}{\bf para todo} $l\in C$ {\bf faça}\\
\hspace{48pt}{\bf se} $i\leq 5$ {\bf e} $k\neq`Mar'$ {\bf então}\\
\hspace{64pt}{\it ação};\\
\end{tabular}
% \noindent\hfil
% \begin{tabular}{@{}l@{}}
% {\bf for all} $i\in A$ {\bf do}\\
% \hspace{16pt}{\bf for all} $(j,k)\in B$ {\bf do}\\
% \hspace{32pt}{\bf for all} $l\in C$ {\bf do}\\
% \hspace{48pt}{\bf if} $i\leq 5$ {\bf and} $k\neq`Mar'$ {\bf then}\\
% \hspace{64pt}{\it action};\\
% \end{tabular}
\noindent Assim, se a expressão indexante fosse usada como uma
expressão de conjunto primária, o conjunto resultante seria o seguinte:
$$\{(4,1,Jan,a),(4,1,Fev,a),(4,2,Abr,a),\dots,(4,3,Jun,c)\}.$$
Se o predicado não é especificado na expressão indexante assume-se um,
que recebe o valor {\it verdadeiro}.
% \noindent Thus, if this indexing expression were used as a primary set
% expression, the resultant set would be the following:
% $$\{(4,1,Jan,a),(4,1,Feb,a),(4,2,Apr,a),\dots,(4,3,Jun,c)\}.$$
%
% If no predicate is specified in the indexing expression, one, which
% takes on the value {\it true}, is assumed.
\section{Expressões de conjunto}
Uma {\it expressão de conjunto} é uma regra para calcular um conjunto
elementar, i.e., uma coleção de $n$-tuplas, onde os componentes das
$n$-tuplas são quantidades numéricas e simbólicas.
% A {\it set expression} is a rule for computing an elemental set, i.e.
% a collection of $n$-tuples, where components of $n$-tuples are numeric
% and symbolic quantities.
A expressão de conjunto primária pode ser um conjunto de literais, um conjunto
não-indexado, um conjunto indexado, um conjunto ``aritmético'', uma expressão
indexante, uma expressão de \linebreak conjunto iterada, uma expressão de conjunto
condicional ou outra expressão cercada por \linebreak parênteses.
\para{Exemplos}
% The primary set expression may be a literal set, unsubscripted set,
% subscripted set, ``arithmetic'' set, indexing expression, iterated set
% expression, conditional set expression, or another set expression
% enclosed in parentheses.
%
% \para{Examples}
\noindent
\begin{tabular}{@{}ll@{}}
\verb|{(123,'aaa'), (i+1,'bbb'), (j-1,'ccc')}| &(conjunto de literais)\\
\verb|I| &(conjunto não-indexado)\\
\verb|S[i-1,j+1]| &(conjunto indexado)\\
\verb|1..t-1 by 2| &(conjunto ``aritmético'')\\
\verb|{t in 1..T, (t+1,j) in S: (t,j) in F}| &(expressão indexante)\\
\verb|setof{i in I, j in J}(i+1,j-1)| &(expressão de conjunto iterado)\\
\verb|if i < j then S[i,j] else F diff S[i,j]| &(expressão de conjunto
condicional)\\
\verb|(1..10 union 21..30)| &(expressão de conjunto parentizado)\\
\end{tabular}
% \noindent
% \begin{tabular}{@{}ll@{}}
% \verb|{(123,'aaa'), (i+1,'bbb'), (j-1,'ccc')}| &(literal set)\\
% \verb|I| &(unsubscripted set)\\
% \verb|S[i-1,j+1]| &(subscripted set)\\
% \verb|1..t-1 by 2| &(``arithmetic'' set)\\
% \verb|{t in 1..T, (t+1,j) in S: (t,j) in F}| &(indexing expression)\\
% \verb|setof{i in I, j in J}(i+1,j-1)| &(iterated set expression)\\
% \verb|if i < j then S[i,j] else F diff S[i,j]| &(conditional set
% expression)\\
% \verb|(1..10 union 21..30)| &(parenthesized set expression)\\
% \end{tabular}
Expressões de conjuntos mais genéricas contendo duas ou mais expressões
de conjunto primárias podem ser construídas usando operadores
específicos de conjunto .
\para{Exemplos}
% More general set expressions containing two or more primary set
% expressions may be constructed by using certain set operators.
%
% \para{Examples}
\begin{verbatim}
(A union B) inter (I cross J)
1..10 cross (if i < j then {'a', 'b', 'c'} else {'d', 'e', 'f'})
\end{verbatim}
\subsection{Conjuntos de literais}
Um {\it conjunto de literais} é uma expressão de conjunto primária
que possui as duas formas \linebreak sintáticas seguintes:
% A {\it literal set} is a primary set expression, which has the
% following two syntactic forms:
$$
{\def\arraystretch{1.4}
\begin{array}{l}
\mbox{{\tt\{}$e_1${\tt,} $e_2${\tt,} \dots{\tt,} $e_m${\tt\}}}\\
\mbox{{\tt\{(}$e_{11}${\tt,} \dots{\tt,} $e_{1n}${\tt),}
{\tt(}$e_{21}${\tt,} \dots{\tt,} $e_{2n}${\tt),} \dots{\tt,}
{\tt(}$e_{m1}${\tt,} \dots{\tt,} $e_{mn}${\tt)\}}}\\
\end{array}
}
$$
% $$
% {\def\arraystretch{1.4}
% \begin{array}{l}
% \mbox{{\tt\{}$e_1${\tt,} $e_2${\tt,} \dots{\tt,} $e_m${\tt\}}}\\
% \mbox{{\tt\{(}$e_{11}${\tt,} \dots{\tt,} $e_{1n}${\tt),}
% {\tt(}$e_{21}${\tt,} \dots{\tt,} $e_{2n}${\tt),} \dots{\tt,}
% {\tt(}$e_{m1}${\tt,} \dots{\tt,} $e_{mn}${\tt)\}}}\\
% \end{array}
% }
% $$
onde $e_1$, \dots, $e_m$, $e_{11}$, \dots, $e_{mn}$ são expressões
numéricas ou simbólicas.
Se a primeira forma é adotada, o conjunto resultante consiste
de 1-tuplas (singletos) enumerados entre as chaves.
É permitido especificar um conjunto vazio como {\tt\{\ \}},
que não possui 1-tuplas. Se a segunda forma é adotada,
o conjunto resultante consiste de $n$-tuplas enumeradas entre as chaves,
onde uma $n$-tupla particular consiste nos componentes correspondentes
enumerados entre parênteses. Todas as $n$-tuplas devem ter o mesmo
número de componentes.
% where $e_1$, \dots, $e_m$, $e_{11}$, \dots, $e_{mn}$ are numeric or
% symbolic expressions.
%
% If the first form is used, the resultant set consists of 1-tuples
% (singlets) enumerated within the curly braces. It is allowed to specify
% an empty set as {\tt\{\ \}}, which has no 1-tuples. If the second form
% is used, the resultant set consists of $n$-tuples enumerated within the
% curly braces, where a particular $n$-tuple consists of corresponding
% components enumerated within the parentheses. All $n$-tuples should
% have the same number of components.
\subsection{Conjuntos não-indexados}
Se a expressão de conjunto primária é um conjunto não-indexado
(que deve ser 0-dimensional), o conjunto resultante é um conjunto
elementar associado com o objeto conjunto correspondente.
% If the primary set expression is an unsubscripted set (which should be
% 0-dimen\-sional), the resultant set is an elemental set associated with
% the corresponding set object.
\subsection{Conjuntos indexados}
A expressão de conjunto primária, que se refere a um conjunto indexado,
tem a seguinte forma sintática:
$$\mbox{{\it nome}{\tt[}$i_1${\tt,} $i_2${\tt,} \dots{\tt,}
$i_n${\tt]}}$$
onde {\it nome} é o nome simbólico do objeto conjunto e $i_1$, $i_2$,
\dots, $i_n$ são subíndices.
% The primary set expression, which refers to a subscripted set, has the
% following syntactic form:
% $$\mbox{{\it name}{\tt[}$i_1${\tt,} $i_2${\tt,} \dots{\tt,}
% $i_n${\tt]}}$$
% where {\it name} is the symbolic name of the set object, $i_1$, $i_2$,
% \dots, $i_n$ are subscripts.
Cada subíndice deve ser uma expressão numérica ou simbólica. O número de
subíndices nas lista de subíndices deve ser o mesmo da dimensão do objeto
conjunto com o qual as lista de subíndice está associada.
Os valores correntes das expressões de subíndices são usados para identificar
um membro \linebreak particular do objeto conjunto que determina o conjunto resultante.
% Each subscript should be a numeric or symbolic expression. The number
% of subscripts in the subscript list should be the same as the dimension
% of the set object with which the subscript list is associated.
%
% Actual values of subscript expressions are used to identify a
% particular member of the set object that determines the resultant set.
\subsection{Conjuntos ``aritméticos''}
A expressão de conjunto primária que constitui um conjunto ``aritmético'',
possui as duas formas sintáticas seguintes:
% The primary set expression, which is an ``arithmetic'' set, has the
% following two syntactic forms:
$$
{\def\arraystretch{1.4}
\begin{array}{l}
\mbox{$t_0$ {\tt..} $t_1$ {\tt by} $\delta t$}\\
\mbox{$t_0$ {\tt..} $t_1$}\\
\end{array}
}
$$
onde $t_0$, $t_1$, e $\delta t$ são expressões numéricas (o valor de
$\delta t$ não deve ser zero). A segunda forma é equivalente a primeira
forma, onde $\delta t=1$.
Se $\delta t>0$, o conjunto resultante é determinado como segue:
$$\{t:\exists k\in{\cal Z}(t=t_0+k\delta t,\ t_0\leq t\leq t_1)\}.$$
Caso contrário, se $\delta t<0$, o conjunto resultante é determinado como segue:
$$\{t:\exists k\in{\cal Z}(t=t_0+k\delta t,\ t_1\leq t\leq t_0)\}.$$
% $$
% {\def\arraystretch{1.4}
% \begin{array}{l}
% \mbox{$t_0$ {\tt..} $t_1$ {\tt by} $\delta t$}\\
% \mbox{$t_0$ {\tt..} $t_1$}\\
% \end{array}
% }
% $$
% where $t_0$, $t_1$, and $\delta t$ are numeric expressions (the value
% of $\delta t$ should not be zero). The second form is equivalent to the
% first form, where $\delta t=1$.
%
% If $\delta t>0$, the resultant set is determined as follows:
% $$\{t:\exists k\in{\cal Z}(t=t_0+k\delta t,\ t_0\leq t\leq t_1)\}.$$
% Otherwise, if $\delta t<0$, the resultant set is determined as follows:
% $$\{t:\exists k\in{\cal Z}(t=t_0+k\delta t,\ t_1\leq t\leq t_0)\}.$$
\subsection{Expressões indexantes}
Se a expressão primária é uma expressão indexante, o conjunto resultante
é determinado como descrito anteriormente, na Seção \ref{indexing}, página
\pageref{indexing}.
% If the primary set expression is an indexing expression, the resultant
% set is determined as described above in Section \ref{indexing}, page
% \pageref{indexing}.
\newpage
\subsection{Expressões iteradas}
Uma {\it expressão de conjunto iterada} é uma expressão de conjunto
primária, que possui a seguinte forma sintática:
$$\mbox{{\tt setof} {\it expressão-indexante} {\it integrando}}$$
onde {\it expressão-indexante} é uma expressão indexante, que
introduz índices e controla a iteração, {\it integrando} é
tanto uma expressão numérica ou simbólica individual, como uma
lista de expressões numéricas ou simbólicas separadas por vírgula
e cercadas entre parênteses.
% An {\it iterated set expression} is a primary set expression, which has
% the following syntactic form:
% $$\mbox{{\tt setof} {\it indexing-expression} {\it integrand}}$$
% where {\it indexing-expression} is an indexing expression, which
% introduces dummy indices and controls iterating, {\it integrand} is
% either a single numeric or symbolic expression or a list of numeric and
% symbolic expressions separated by commae and enclosed in parentheses.
Se o integrando é uma expressão numérica ou simbólica individual, o
conjunto resultante consiste de 1-tuplas, sendo determinado como segue:
$$\{x:(i_1,\dots,i_n)\in\Delta\},$$
\noindent onde $x$ é um valor do integrando, $i_1$, \dots, $i_n$
são índices introduzidos na expressão indexante, $\Delta$ é
o domínio, um conjunto de $n$-tuplas especificado pela expressão
indexante que define valores particulares atribuídos aos índices ao
realizar a operação de iteração.
% If the integrand is a single numeric or symbolic expression, the
% resultant set consists of 1-tuples and is determined as follows:
% $$\{x:(i_1,\dots,i_n)\in\Delta\},$$
% \noindent where $x$ is a value of the integrand, $i_1$, \dots, $i_n$
% are dummy indices introduced in the indexing expression, $\Delta$ is
% the domain, a set of $n$-tuples specified by the indexing expression,
% which defines particular values assigned to the dummy indices on
% performing the iterated operation.
Se o integrando é uma lista contendo $m$ expressões numéricas e simbólicas,
o conjunto resultante consiste de $m$-tuplas, sendo determinado
como segue:
$$\{(x_1,\dots,x_m):(i_1,\dots,i_n)\in\Delta\},$$
onde $x_1$, \dots, $x_m$ são valores das expressões na lista
de integrandos, $i_1$, \dots, $i_n$ e $\Delta$ possuem o mesmo significado
anterior.
% If the integrand is a list containing $m$ numeric and symbolic
% expressions, the resultant set consists of $m$-tuples and is determined
% as follows:
% $$\{(x_1,\dots,x_m):(i_1,\dots,i_n)\in\Delta\},$$
% where $x_1$, \dots, $x_m$ are values of the expressions in the
% integrand list, $i_1$, \dots, $i_n$ and $\Delta$ have the same meaning
% as above.
\subsection{Expressões condicionais}
Uma {\it expressão de conjunto condicional} é uma expressão de conjunto
primária que possui a seguinte forma sintática:
$$\mbox{{\tt if} $b$ {\tt then} $X$ {\tt else} $Y$}$$
onde $b$ é uma expressão lógica, $X$ e $Y$ são expressões de conjunto,
que devem definir conjuntos da mesma dimensão.
% A {\it conditional set expression} is a primary set expression that has
% the following syntactic form:
% $$\mbox{{\tt if} $b$ {\tt then} $X$ {\tt else} $Y$}$$
% where $b$ is an logical expression, $X$ and $Y$ are set expressions,
% which should define sets of the same dimension.
O valor resultante da expressão condicional depende do valor da
expressão lógica que segue a palavra-chave {\tt if}. Se ela recebe
o valor {\it verdadeiro}, o conjunto resultante é o valor da expressão
que segue a palavra-chave {\tt then}. Caso contrário, se a
expressão lógica recebe o valor {\it falso}, o conjunto resultante é
o valor da expressão que segue a palavra-chave {\tt else}.
% The resultant value of the conditional expression depends on the value
% of the logical expression that follows the keyword {\tt if}. If it
% takes on the value {\it true}, the resultant set is the value of the
% expression that follows the keyword {\tt then}. Otherwise, if the
% logical expression takes on the value {\it false}, the resultant set is
% the value of the expression that follows the keyword {\tt else}.
\subsection{Expressões parentizadas}
Qualquer expressão de conjunto pode ser cercada entre parênteses, o que as tornam
\linebreak sintaticamente uma expressão de conjunto primária.
Parênteses podem ser usados em expressões de conjunto, como em álgebra, para
especificar a ordem desejada nas quais as operações devem ser executadas.
Quando se usam parênteses, a expressão entre parênteses é avaliada
antes que o valor resultante seja usado.
O valor resultante de uma expressão parentizada é idêntico ao valor da expressão
cercada entre parênteses.
% Any set expression may be enclosed in parentheses that syntactically
% makes it a primary set expression.
%
% Parentheses may be used in set expressions, as in algebra, to specify
% the desired order in which operations are to be performed. Where
% parentheses are used, the expression within the parentheses is
% evaluated before the resultant value is used.
%
% The resultant value of the parenthesized expression is the same as the
% value of the expression enclosed within parentheses.
\newpage
\subsection{Operadores de conjunto}
Em MathProg existem os seguintes operadores de conjunto, que podem ser
usados em expressões de conjunto:
% In MathProg there exist the following set operators, which may be used
% in set expressions:
\begin{tabular}{@{}ll@{}}
$X$ {\tt union} $Y$&união $X\cup Y$\\
$X$ {\tt diff} $Y$&diferença $X\backslash Y$\\
$X$ {\tt symdiff} $Y$&diferença simétrica
$X\oplus Y=(X\backslash Y)\cup(Y\backslash X)$\\
$X$ {\tt inter} $Y$&interseção $X\cap Y$\\
$X$ {\tt cross} $Y$&produto Cartesiano (cruzado) $X\times Y$\\
\end{tabular}
% \begin{tabular}{@{}ll@{}}
% $X$ {\tt union} $Y$&union $X\cup Y$\\
% $X$ {\tt diff} $Y$&difference $X\backslash Y$\\
% $X$ {\tt symdiff} $Y$&symmetric difference
% $X\oplus Y=(X\backslash Y)\cup(Y\backslash X)$\\
% $X$ {\tt inter} $Y$&intersection $X\cap Y$\\
% $X$ {\tt cross} $Y$&cross (Cartesian) product $X\times Y$\\
% \end{tabular}
\noindent onde $X$ e Y são expressões de conjunto, que devem definir conjuntos
de dimensões idênticas (exceto o produto Cartesiano).
Se a expressão inclui mais de um operador de conjunto, todos operadores
são executados da esquerda para a direita de acordo com a hierarquia das
operações (veja adiante).
O valor resultante da expressão, que contém operadores de conjunto, é
o resultado da aplicação dos operadores aos seus operandos.
A dimensão do conjunto resultante, i.e., a dimensão das $n$-tuplas,
dos quais consistem o conjunto resultante, é a mesma da dimensão dos
operandos, exceto o produto Cartesiano, onde a dimensão do conjunto
resultante é a soma das dimensões dos seus operandos.
% \noindent where $X$ and Y are set expressions, which should define sets
% of identical dimension (except the Cartesian product).
%
% If the expression includes more than one set operator, all operators
% are performed from left to right according to the hierarchy of
% operations (see below).
%
% The resultant value of the expression, which contains set operators, is
% the result of applying the operators to their operands.
%
% The dimension of the resultant set, i.e. the dimension of $n$-tuples,
% of which the resultant set consists of, is the same as the dimension of
% the operands, except the Cartesian product, where the dimension of the
% resultant set is the sum of the dimensions of its operands.
\subsection{Hierarquia das operações}
A lista seguinte mostra a hierarquia das operações em expressões de conjunto:
% The following list shows the hierarchy of operations in set
% expressions:
\noindent\hfil
\begin{tabular}{@{}ll@{}}
Operação&Hierarquia\\
\hline
Avaliação de operações numéricas&
1{\textsuperscript{\b{a}}}-7{\textsuperscript{\b{a}}}\\
Avaliação de operações simbólicas&
8{\textsuperscript{\b{a}}}-9{\textsuperscript{\b{a}}}\\
Avaliação de conjuntos iterados ou ``aritméticos'' ({\tt setof}, {\tt..})&
10{\textsuperscript{\b{a}}}\\
Produto Cartesiano ({\tt cross})&
11{\textsuperscript{\b{a}}}\\
Interseção ({\tt inter})&
12{\textsuperscript{\b{a}}}\\
União e diferença ({\tt union}, {\tt diff}, {\tt symdiff})&
13{\textsuperscript{\b{a}}}\\
Avaliação condicional ({\tt if} \dots {\tt then} \dots {\tt else})&
14{\textsuperscript{\b{a}}}\\
\end{tabular}
% \noindent\hfil
% \begin{tabular}{@{}ll@{}}
% Operation&Hierarchy\\
% \hline
% Evaluation of numeric operations&1st-7th\\
% Evaluation of symbolic operations&8th-9th\\
% Evaluation of iterated or ``arithmetic'' set ({\tt setof}, {\tt..})&
% 10th\\
% Cartesian product ({\tt cross})&11th\\
% Intersection ({\tt inter})&12th\\
% Union and difference ({\tt union}, {\tt diff}, {\tt symdiff})&13th\\
% Conditional evaluation ({\tt if} \dots {\tt then} \dots {\tt else})&
% 14th\\
% \end{tabular}
Esta hierarquia possui o mesmo significado como explicado anteriormente
para expressões \linebreak numéricas (ver Subseção \ref{hierarchy}, página \pageref{hierarchy}).
% This hierarchy has the same meaning as was explained above for numeric
% expressions (see Subsection \ref{hierarchy}, page \pageref{hierarchy}).
\newpage
\section{Expressões lógicas}
Uma {\it expressão lógica} é uma regra para calcular um valor lógico
individual, que pode ser {\it verdadeiro} ou {\it falso}.
A expressão lógica primária pode ser uma expressão numérica,
uma expressão relacional, uma expressão lógica iterada ou
outra expressão lógica cercada entre parênteses.
\para{Exemplos}
% A {\it logical expression} is a rule for computing a single logical
% value, which can be either {\it true} or {\it false}.
%
% The primary logical expression may be a numeric expression, relational
% expression, iterated logical expression, or another logical expression
% enclosed in parentheses.
%
% \para{Examples}
\noindent
\begin{tabular}{@{}ll@{}}
\verb|i+1| &(expressão numérica)\\
\verb|a[i,j] < 1.5| &(expressão relacional)\\
\verb|s[i+1,j-1] <> 'Mar' & year | &(expressão relacional)\\
\verb|(i+1,'Jan') not in I cross J| &(expressão relacional)\\
\verb|S union T within A[i] inter B[j]| &(expressão relacional)\\
\verb|forall{i in I, j in J} a[i,j] < .5 * b[i]| &(expressão lógica iterada)\\
\verb|(a[i,j] < 1.5 or b[i] >= a[i,j])| &(expressão lógica parentizada)\\
\end{tabular}
% \noindent
% \begin{tabular}{@{}ll@{}}
% \verb|i+1| &(numeric expression)\\
% \verb|a[i,j] < 1.5| &(relational expression)\\
% \verb|s[i+1,j-1] <> 'Mar' & year | &(relational expression)\\
% \verb|(i+1,'Jan') not in I cross J| &(relational expression)\\
% \verb|S union T within A[i] inter B[j]| &(relational expression)\\
% \verb|forall{i in I, j in J} a[i,j] < .5 * b[i]| &(iterated logical
% expression)\\
% \verb|(a[i,j] < 1.5 or b[i] >= a[i,j])| &(parenthesized logical
% expression)\\
% \end{tabular}
Expressões lógicas mais genéricas, contendo duas ou mais
expressões lógicas primárias, podem ser construídas usando
determinados operadores lógicos.
\para{Exemplos}
\begin{verbatim}
not (a[i,j] < 1.5 or b[i] >= a[i,j]) and (i,j) in S
(i,j) in S or (i,j) not in T diff U
\end{verbatim}
% More general logical expressions containing two or more primary logical
% expressions may be constructed by using certain logical operators.
%
% \para{Examples}
%
% \begin{verbatim}
% not (a[i,j] < 1.5 or b[i] >= a[i,j]) and (i,j) in S
% (i,j) in S or (i,j) not in T diff U
% \end{verbatim}
\vspace*{-8pt}
\subsection{Expressões numéricas}
O valor resultante da expressão lógica primária, que é uma
expressão numérica, é {\it verdadeiro}, se o valor resultante da
expressão numérica é diferente de zero. Caso contrário o valor resultante
da expressão lógica é {\it falso}.
% The resultant value of the primary logical expression, which is a
% numeric expression, is {\it true}, if the resultant value of the
% numeric expression is non-zero. Otherwise the resultant value of the
% logical expression is {\it false}.
\vspace*{-8pt}
\subsection{Operadores relacionais}
Em MathProg existem os seguintes operadores relacionais, que podem
ser usados em expressões lógicas:
% In MathProg there exist the following relational operators, which may
% be used in logical expressions:
\begin{tabular}{@{}ll@{}}
$x$ {\tt<} $y$&verifica se $x<y$\\
$x$ {\tt<=} $y$&verifica se $x\leq y$\\
$x$ {\tt=} $y$, $x$ {\tt==} $y$&verifica se $x=y$\\
$x$ {\tt>=} $y$&verifica se $x\geq y$\\
$x$ {\tt>} $y$&verifica se $x>y$\\
$x$ {\tt<>} $y$, $x$ {\tt!=} $y$&verifica se $x\neq y$\\
$x$ {\tt in} $Y$&verifica se $x\in Y$\\
{\tt(}$x_1${\tt,}\dots{\tt,}$x_n${\tt)} {\tt in} $Y$&verifica se
$(x_1,\dots,x_n)\in Y$\\
$x$ {\tt not} {\tt in} $Y$, $x$ {\tt!in} $Y$&verifica se $x\not\in Y$\\
{\tt(}$x_1${\tt,}\dots{\tt,}$x_n${\tt)} {\tt not} {\tt in} $Y$,
{\tt(}$x_1${\tt,}\dots{\tt,}$x_n${\tt)} {\tt !in} $Y$&verifica se
$(x_1,\dots,x_n)\not\in Y$\\
$X$ {\tt within} $Y$&verifica se $X\subseteq Y$\\
$X$ {\tt not} {\tt within} $Y$, $X$ {\tt !within} $Y$&verifica se
$X\not\subseteq Y$\\
\end{tabular}
% \begin{tabular}{@{}ll@{}}
% $x$ {\tt<} $y$&test on $x<y$\\
% $x$ {\tt<=} $y$&test on $x\leq y$\\
% $x$ {\tt=} $y$, $x$ {\tt==} $y$&test on $x=y$\\
% $x$ {\tt>=} $y$&test on $x\geq y$\\
% $x$ {\tt>} $y$&test on $x>y$\\
% $x$ {\tt<>} $y$, $x$ {\tt!=} $y$&test on $x\neq y$\\
% $x$ {\tt in} $Y$&test on $x\in Y$\\
% {\tt(}$x_1${\tt,}\dots{\tt,}$x_n${\tt)} {\tt in} $Y$&test on
% $(x_1,\dots,x_n)\in Y$\\
% $x$ {\tt not} {\tt in} $Y$, $x$ {\tt!in} $Y$&test on $x\not\in Y$\\
% {\tt(}$x_1${\tt,}\dots{\tt,}$x_n${\tt)} {\tt not} {\tt in} $Y$,
% {\tt(}$x_1${\tt,}\dots{\tt,}$x_n${\tt)} {\tt !in} $Y$&test on
% $(x_1,\dots,x_n)\not\in Y$\\
% $X$ {\tt within} $Y$&test on $X\subseteq Y$\\
% $X$ {\tt not} {\tt within} $Y$, $X$ {\tt !within} $Y$&test on
% $X\not\subseteq Y$\\
% \end{tabular}
\noindent onde $x$, $x_1$, \dots, $x_n$, $y$ são expressões numéricas ou
simbólicas, $X$ e $Y$ são expressões de conjunto.
% \noindent where $x$, $x_1$, \dots, $x_n$, $y$ are numeric or symbolic
% expressions, $X$ and $Y$ are set expression.
\newpage
1. Nas operações {\tt in}, {\tt not in} e {\tt !in} o número
de componentes nos primeiros operandos deve ser igual a
dimensão do segundo operando.
2. Nas operações {\tt within}, {\tt not within} e {\tt !within}
ambos operandos devem ter a mesma dimensão.
Todos operadores relacionais listados acima têm seus significados
matemáticos convencionais. O valor resultante é {\it verdadeiro}, se
a relação correspondente é satisfeita para seus operandos, caso contrário
é {\it falso}. (Note que valores simbólicos são ordenados de forma
lexicográfica e qualquer valor numérico precede qualquer valor simbólico.)
% 1. In the operations {\tt in}, {\tt not in}, and {\tt !in} the
% number of components in the first operands should be the same as the
% dimension of the second operand.
%
% 2. In the operations {\tt within}, {\tt not within}, and {\tt !within}
% both operands should have identical dimension.
%
% All the relational operators listed above have their conventional
% mathematical meaning. The resultant value is {\it true}, if
% corresponding relation is satisfied for its operands, otherwise
% {\it false}. (Note that symbolic values are ordered lexicographically,
% and any numeric value precedes any symbolic value.)
\subsection{Expressões iteradas}
Uma {\it expressão lógica iterada} é uma expressão lógica primária
com a seguinte forma sintática:
$$\mbox{{\it operador-iterado} {\it expressão-indexante}
{\it integrando}}$$
onde {\it operador-iterado} é o nome simbólico do operador iterado
a ser executado (veja adiante), {\it expressão-indexante} é uma
expressão indexante que introduz índices e controla a iteração, \linebreak
{\it integrando} é uma expressão numérica que participa da operação.
Em MathProg existem dois operadores iterados que podem ser usados
em expressões lógicas:
% An {\it iterated logical expression} is a primary logical expression,
% which has the following syntactic form:
% $$\mbox{{\it iterated-operator} {\it indexing-expression}
% {\it integrand}}$$
% where {\it iterated-operator} is the symbolic name of the iterated
% operator to be performed (see below), {\it indexing-expression} is an
% indexing expression which introduces dummy indices and controls
% iterating, {\it integrand} is a numeric expression that participates in
% the operation.
%
% In MathProg there exist two iterated operators, which may be used in
% logical expressions:
{\def\arraystretch{1.4}
\noindent\hfil
\begin{tabular}{@{}lll@{}}
{\tt forall}&quantificador-$\forall$&$\displaystyle
\forall(i_1,\dots,i_n)\in\Delta[f(i_1,\dots,i_n)],$\\
{\tt exists}&quantificador-$\exists$&$\displaystyle
\exists(i_1,\dots,i_n)\in\Delta[f(i_1,\dots,i_n)],$\\
\end{tabular}
}
% {\def\arraystretch{1.4}
% \noindent\hfil
% \begin{tabular}{@{}lll@{}}
% {\tt forall}&$\forall$-quantification&$\displaystyle
% \forall(i_1,\dots,i_n)\in\Delta[f(i_1,\dots,i_n)],$\\
% {\tt exists}&$\exists$-quantification&$\displaystyle
% \exists(i_1,\dots,i_n)\in\Delta[f(i_1,\dots,i_n)],$\\
% \end{tabular}
% }
\noindent onde $i_1$, \dots, $i_n$ são índices introduzidos na
expressão indexante, $\Delta$ é o domínio, um conjunto de $n$-tuplas
especificado pela expressão indexante que define valores específicos
atribuídos aos índices ao executar a operação iterada, e
$f(i_1,\dots,i_n)$ é o integrando, uma expressão lógica cujo
valor resultante depende dos índices.
Para o quantificador $\forall$, o valor resultante da expressão
lógica iterada é {\it verdadeiro}, se o valor do integrando é
{\it verdadeiro} para todas as $n$-tuplas contidas no domínio,
caso contrário, é {\it falso}.
Para o quantificador $\exists$ o valor resultante da expressão
lógica iterada é {\it falso}, se o valor do integrando é
{\it falso} para todas as $n$-tuplas contidas no domínio,
caso contrário, é {\it verdadeiro}.
% \noindent where $i_1$, \dots, $i_n$ are dummy indices introduced in
% the indexing expression, $\Delta$ is the domain, a set of $n$-tuples
% specified by the indexing expression which defines particular values
% assigned to the dummy indices on performing the iterated operation,
% $f(i_1,\dots,i_n)$ is the integrand, a logical expression whose
% resultant value depends on the dummy indices.
%
% For $\forall$-quantification the resultant value of the iterated
% logical expression is {\it true}, if the value of the integrand is
% {\it true} for all $n$-tuples contained in the domain, otherwise
% {\it false}.
%
% For $\exists$-quantification the resultant value of the iterated
% logical expression is {\it false}, if the value of the integrand is
% {\it false} for all $n$-tuples contained in the domain, otherwise
% {\it true}.
\subsection{Expressões parentizadas}
Qualquer expressão lógica pode ser cercada entre parênteses, o que a
converte sintaticamente em uma expressão lógica primária.
Parênteses podem ser usados em expressões lógicas, como em álgebra, para
especificar a ordem desejada na qual as operações devem ser executadas.
Quando se usam parênteses, a expressão entre parênteses é avaliada antes
que o valor resultante seja usado.
O valor resultante da expressão parentizada é idêntico ao valor da expressão
cercada entre parênteses.
% Any logical expression may be enclosed in parentheses that
% syntactically makes it a primary logical expression.
%
% Parentheses may be used in logical expressions, as in algebra, to
% specify the desired order in which operations are to be performed.
% Where parentheses are used, the expression within the parentheses is
% evaluated before the resultant value is used.
%
% The resultant value of the parenthesized expression is the same as the
% value of the expression enclosed within parentheses.
\newpage
\subsection{Operadores lógicos}
Em MathProg existem os seguintes operadores lógicos, que podem ser usados em
expressões lógicas:
% In MathProg there exist the following logical operators, which may be
% used in logical expressions:
\begin{tabular}{@{}ll@{}}
{\tt not} $x$, {\tt!}$x$&negação $\neg\ x$\\
$x$ {\tt and} $y$, $x$ {\tt\&\&} $y$&conjunção (``e'' lógico)
$x\;\&\;y$\\
$x$ {\tt or} $y$, $x$ {\tt||} $y$&disjunção (``ou'' lógico)
$x\vee y$\\
\end{tabular}
% \begin{tabular}{@{}ll@{}}
% {\tt not} $x$, {\tt!}$x$&negation $\neg\ x$\\
% $x$ {\tt and} $y$, $x$ {\tt\&\&} $y$&conjunction (logical ``and'')
% $x\;\&\;y$\\
% $x$ {\tt or} $y$, $x$ {\tt||} $y$&disjunction (logical ``or'')
% $x\vee y$\\
% \end{tabular}
\noindent onde $x$ e $y$ são expressões lógicas.
Se a expressão inclui mais de um operador lógico, todos operadores
são executados da esquerda para a direita de acordo com a hierarquia
das operações (veja adiante). O valor resultante da \linebreak expressão
que contém operadores lógicos é o resultado da aplicação dos
operadores aos seus \linebreak operandos.
% \noindent where $x$ and $y$ are logical expressions.
%
% If the expression includes more than one logical operator, all
% operators are performed from left to right according to the hierarchy
% of the operations (see below). The resultant value of the expression,
% which contains logical operators, is the result of applying the
% operators to their operands.
\subsection{Hierarquia das operações}
A lista seguinte mostra a hierarquia das operações em expressões
lógicas:
% The following list shows the hierarchy of operations in logical
% expressions:
\noindent\hfil
\begin{tabular}{@{}ll@{}}
Operation&Hierarchy\\
\hline
Avaliação de operações numéricas&
1{\textsuperscript{\b{a}}}-7{\textsuperscript{\b{a}}}\\
Avaliação de operações simbólicas&
8{\textsuperscript{\b{a}}}-9{\textsuperscript{\b{a}}}\\
Avaliação de operações de conjunto&
10{\textsuperscript{\b{a}}}-14{\textsuperscript{\b{a}}}\\
Operações relacionais ({\tt<}, {\tt<=}, etc.)&
15{\textsuperscript{\b{a}}}\\
negação ({\tt not}, {\tt!})&
16{\textsuperscript{\b{a}}}\\
Conjunção({\tt and}, {\tt\&\&})&
17{\textsuperscript{\b{a}}}\\
Quantificação-$\forall$ e -$\exists$ ({\tt forall}, {\tt exists})&
18{\textsuperscript{\b{a}}}\\
Disjunção ({\tt or}, {\tt||})&
19{\textsuperscript{\b{a}}}\\
\end{tabular}
% \noindent\hfil
% \begin{tabular}{@{}ll@{}}
% Operation&Hierarchy\\
% \hline
% Evaluation of numeric operations&1st-7th\\
% Evaluation of symbolic operations&8th-9th\\
% Evaluation of set operations&10th-14th\\
% Relational operations ({\tt<}, {\tt<=}, etc.)&15th\\
% Negation ({\tt not}, {\tt!})&16th\\
% Conjunction ({\tt and}, {\tt\&\&})&17th\\
% $\forall$- and $\exists$-quantification ({\tt forall}, {\tt exists})&
% 18th\\
% Disjunction ({\tt or}, {\tt||})&19th\\
% \end{tabular}
Esta hierarquia possui o mesmo significado como explicado anteriormente
para expressões \linebreak numéricas (ver Subseção \ref{hierarchy}, página \pageref{hierarchy}).
% This hierarchy has the same meaning as was explained above for numeric
% expressions (see Subsection \ref{hierarchy}, page \pageref{hierarchy}).
\newpage
\section{Expressões lineares}
Uma {\it expressão linear} é uma regra para calcular a chamada
{\it forma linear} ou simplesmente {\it fórmula}, que é uma função linear (ou
afim) de variáveis elementares.
A expressão linear primária pode ser uma variável não-indexada, uma
variável indexada, uma expressão linear iterada, uma expressão linear condicional
ou outra expressão linear cercada entre parênteses.
Também e permitido usar uma expressão numérica como a expressão linear
primária, neste caso, o valor resultante da expressão numérica
é automaticamente convertido para uma fórmula que inclui o
termo constante apenas.
\para{Exemplos}
% A {\it linear expression} is a rule for computing so called
% a {\it linear form} or simply a {\it formula}, which is a linear (or
% affine) function of elemental variables.
%
% The primary linear expression may be an unsubscripted variable,
% subscripted variable, iterated linear expression, conditional linear
% expression, or another linear expression enclosed in parentheses.
%
% It is also allowed to use a numeric expression as the primary linear
% expression, in which case the resultant value of the numeric expression
% is automatically converted to a formula that includes the constant term
% only.
%
% \para{Examples}
\noindent
\begin{tabular}{@{}ll@{}}
\verb|z| &(variável não-indexada)\\
\verb|x[i,j]| &(variável indexada)\\
\verb|sum{j in J} (a[i,j] * x[i,j] + 3 * y[i-1])| &
(expressão linear iterada)\\
\verb|if i in I then x[i,j] else 1.5 * z + 3.25| &
(expressão linear condicional)\\
\verb|(a[i,j] * x[i,j] + y[i-1] + .1)| &
(expressão linear parentizada)\\
\end{tabular}
% \noindent
% \begin{tabular}{@{}ll@{}}
% \verb|z| &(unsubscripted variable)\\
% \verb|x[i,j]| &(subscripted variable)\\
% \verb|sum{j in J} (a[i,j] * x[i,j] + 3 * y[i-1])| &
% (iterated linear expression)\\
% \verb|if i in I then x[i,j] else 1.5 * z + 3.25| &
% (conditional linear expression)\\
% \verb|(a[i,j] * x[i,j] + y[i-1] + .1)| &
% (parenthesized linear expression)\\
% \end{tabular}
Expressões lineares mais genéricas, contendo duas ou mais
expressões lineares primárias, podem ser construídas usando
determinados operadores aritméticos.
\para{Exemplos}
% More general linear expressions containing two or more primary linear
% expressions may be constructed by using certain arithmetic operators.
%
% \para{Examples}
\begin{verbatim}
2 * x[i-1,j+1] + 3.5 * y[k] + .5 * z
(- x[i,j] + 3.5 * y[k]) / sum{t in T} abs(d[i,j,t])
\end{verbatim}
\vspace*{-5pt}
\subsection{Variáveis não-indexadas}
Se a expressão linear primária é uma variável não-indexada (que deve
se 0-dimensional), a fórmula resultante formula é aquela variável
não-indexada.
% If the primary linear expression is an unsubscripted variable (which
% should be 0-dimensional), the resultant formula is that unsubscripted
% variable.
\vspace*{-5pt}
\subsection{Variáveis indexadas}
A expressão linear primária que se refere a uma variável indexada possui
a seguinte forma sintática:
$$\mbox{{\it nome}{\tt[}$i_1${\tt,} $i_2${\tt,} \dots{\tt,}
$i_n${\tt]}}$$
onde {\it nome} é o nome simbólico da variável do modelo, $i_1$,
$i_2$, \dots, $i_n$ são subíndices.
Cada subíndice deve ser uma expressão numérica ou simbólica. O número
de subíndices na lista de subíndices deve ser igual ao da dimensão da
variável do modelo com a qual está associada a lista de subíndices.
Os valores correntes das expressões dos subíndices são usados para identificar
um membro \linebreak particular da variável do modelo que determina a fórmula resultante,
que é uma variável elementar associada com o membro correspondente.
% The primary linear expression, which refers to a subscripted variable,
% has the following syntactic form:
% $$\mbox{{\it name}{\tt[}$i_1${\tt,} $i_2${\tt,} \dots{\tt,}
% $i_n${\tt]}}$$
% where {\it name} is the symbolic name of the model variable, $i_1$,
% $i_2$, \dots, $i_n$ are subscripts.
%
% Each subscript should be a numeric or symbolic expression. The number
% of subscripts in the subscript list should be the same as the dimension
% of the model variable with which the subscript list is associated.
%
% Actual values of the subscript expressions are used to identify a
% particular member of the model variable that determines the resultant
% formula, which is an elemental variable associated with corresponding
% member.
\vspace*{-5pt}
\subsection{Expressões iteradas}
Uma {\it expressão linear iterada} é uma expressão linear primária,
que tem a seguinte forma sintática:
$$\mbox{{\tt sum} {\it expressão-indexante} {\it integrando}}$$
onde {\it expressão-indexante} é uma expressão indexante, que
introduz índices e controla iterações, {\it integrando} é
uma expressão linear que participa da operação.
A expressão linear iterada é avaliada exatamente da mesma forma que a
expressão numérica iterada (ver Subseção \ref{itexpr}, página
\pageref{itexpr}), exceto que o integrando participante do
somatório é uma fórmula e não um valor numérico.
% An {\it iterated linear expression} is a primary linear expression,
% which has the following syntactic form:
% $$\mbox{{\tt sum} {\it indexing-expression} {\it integrand}}$$
% where {\it indexing-expression} is an indexing expression, which
% introduces dummy indices and controls iterating, {\it integrand} is
% a linear expression that participates in the operation.
%
% The iterated linear expression is evaluated exactly in the same way as
% the iterated numeric expression (see Subection \ref{itexpr}, page
% \pageref{itexpr}) with exception that the integrand participated in the
% summation is a formula, not a numeric value.
\vspace*{-5pt}
\subsection{Expressões condicionais}
Uma {\it expressão linear condicional} é uma expressão linear primária,
que possui uma das duas formas sintáticas seguintes:
$$
{\def\arraystretch{1.4}
\begin{array}{l}
\mbox{{\tt if} $b$ {\tt then} $f$ {\tt else} $g$}\\
\mbox{{\tt if} $b$ {\tt then} $f$}\\
\end{array}
}
$$
onde $b$ é uma expressão lógica, $f$ e $g$ são expressões lineares.
% A {\it conditional linear expression} is a primary linear expression,
% which has one of the following two syntactic forms:
% $$
% {\def\arraystretch{1.4}
% \begin{array}{l}
% \mbox{{\tt if} $b$ {\tt then} $f$ {\tt else} $g$}\\
% \mbox{{\tt if} $b$ {\tt then} $f$}\\
% \end{array}
% }
% $$
% where $b$ is an logical expression, $f$ and $g$ are linear expressions.
% \newpage
A expressão linear condicional é avaliada exatamente da mesma forma
que a expressão \linebreak condicional numérica (ver Subseção \ref{ifthen},
página \pageref{ifthen}), exceto que os operandos que participam da operação
são fórmulas e não valores numéricos.
% The conditional linear expression is evaluated exactly in the same way
% as the conditional numeric expression (see Subsection \ref{ifthen},
% page \pageref{ifthen}) with exception that operands participated in the
% operation are formulae, not numeric values.
\subsection{Expressões parentizadas}
Qualquer expressão linear pode ser cercada entre parênteses, o que a
converte sintaticamente em uma expressão linear primária.
Parênteses podem ser usados em expressões lineares, como em álgebra, para
especificar a ordem desejada na qual as operações devem ser executadas.
Quando se usam parênteses, a expressão entre parênteses é avaliada antes
que a fórmula resultante seja usada.
O valor resultante da expressão parentizada é idêntico ao valor da
expressão cercada entre parênteses.
% Any linear expression may be enclosed in parentheses that syntactically
% makes it a primary linear expression.
%
% Parentheses may be used in linear expressions, as in algebra, to
% specify the desired order in which operations are to be performed.
% Where parentheses are used, the expression within the parentheses is
% evaluated before the resultant formula is used.
%
% The resultant value of the parenthesized expression is the same as the
% value of the expression enclosed within parentheses.
\subsection{Operadores aritméticos}
Em MathProg existem os seguintes operadores aritméticos, que podem ser
usados em expressões lineares:
% In MathProg there exists the following arithmetic operators, which may
% be used in linear expressions:
\begin{tabular}{@{}ll@{}}
{\tt+} $f$&mais unário\\
{\tt-} $f$&menos unário\\
$f$ {\tt+} $g$&adição\\
$f$ {\tt-} $g$&subtração\\
$x$ {\tt*} $f$, $f$ {\tt*} $x$&multiplicação\\
$f$ {\tt/} $x$&divisão
\end{tabular}
% \begin{tabular}{@{}ll@{}}
% {\tt+} $f$&unary plus\\
% {\tt-} $f$&unary minus\\
% $f$ {\tt+} $g$&addition\\
% $f$ {\tt-} $g$&subtraction\\
% $x$ {\tt*} $f$, $f$ {\tt*} $x$&multiplication\\
% $f$ {\tt/} $x$&division
% \end{tabular}
\noindent onde $f$ e $g$ são expressões lineares, $x$ é uma expressão
numérica (mais precisamente, uma expressão linear contendo apenas o termo
constante).
Se a expressão inclui mais de um operador aritmético, todos
operadores são executados da esquerda para a direita de acordo com a hierarquia
das operações (veja adiante). O valor resultante da expressão, que
contém operadores aritméticos, é o resultado de aplicar os operadores aos
seus operandos.
% \noindent where $f$ and $g$ are linear expressions, $x$ is a numeric
% expression (more precisely, a linear expression containing only the
% constant term).
%
% If the expression includes more than one arithmetic operator, all
% operators are performed from left to right according to the hierarchy
% of operations (see below). The resultant value of the expression, which
% contains arithmetic operators, is the result of applying the operators
% to their operands.
\subsection{Hierarquia das operações}
A hierarquia de operações aritméticas usada em expressões lineares é a mesma
para expressões numéricas (ver Subseção \ref{hierarchy}, página \pageref{hierarchy}).
% The hierarchy of arithmetic operations used in linear expressions is
% the same as for numeric expressions (see Subsection \ref{hierarchy},
% page \pageref{hierarchy}).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\chapter{Sentenças}
{\it Sentenças} são unidades básicas da descrição do modelo. Em MathProg
todas as sentenças são divididas em duas categorias: sentenças de declaração
e sentenças funcionais.
{\it Sentenças de declaração} (sentença {\it set}, sentença {\it parameter},
sentença {\it variable}, sentença \linebreak {\it constraint}, sentença {\it objective}) são
usados para declarar objetos de certo tipo do modelo e definir certas propriedades
de tais objetos.
{\it Sentenças funcionais} (sentença {\it solve}, sentença {\it check},
sentença {\it display}, sentença {\it printf}, sentença {\it loop}, sentença
{\it table}) são projetadas para executar ações específicas.
Note que sentenças de declaração podem seguir em qualquer ordem arbitrária,
o que não afeta o resultado da tradução. Entretanto, qualquer objeto de modelo
deve ser declarado antes de ser referenciado por outras sentenças.
% {\it Statements} are basic units of the model description. In MathProg
% all statements are divided into two categories: declaration statements
% and functional statements.
%
% {\it Declaration statements} (set statement, parameter statement,
% variable statement, constraint statement, objective statement) are used
% to declare model objects of certain kinds and define certain properties
% of such objects.
%
% {\it Functional statements} (solve statement, check statement, display
% statement, printf statement, loop statement, table statement) are
% intended for performing some specific actions.
%
% Note that declaration statements may follow in arbitrary order, which
% does not affect the result of translation. However, any model object
% should be declared before it is referenced in other statements.
\section{Sentença set}
\noindent
\framebox[468pt][l]{
\parbox[c][24pt]{468pt}{
\hspace{6pt} {\tt set} {\it nome} {\it alias} {\it domínio} {\tt,}
{\it atributo} {\tt,} \dots {\tt,} {\it atributo} {\tt;}
}}
% \noindent
% \framebox[468pt][l]{
% \parbox[c][24pt]{468pt}{
% \hspace{6pt} {\tt set} {\it name} {\it alias} {\it domain} {\tt,}
% {\it attrib} {\tt,} \dots {\tt,} {\it attrib} {\tt;}
% }}
\medskip
\noindent
{\it nome} é um nome simbólico do conjunto;
\noindent
{\it alias} é um literal de cadeia opcional que especifica um pseudônimo
para o conjunto;
\noindent
{\it domínio} é uma expressão indexante opcional que especifica o domínio
do subíndice do conjunto;
\noindent
{\it atributo}, \dots, {\it atributo} são atributos opcionais do conjunto
(as vírgulas que precedem os atributos podem ser omitidas.)
\para{Atributos opcionais}
% \noindent
% {\it name} is a symbolic name of the set;
%
% \noindent
% {\it alias} is an optional string literal, which specifies an alias of
% the set;
%
% \noindent
% {\it domain} is an optional indexing expression, which specifies
% a subscript domain of the set;
%
% \noindent
% {\it attrib}, \dots, {\it attrib} are optional attributes of the set.
% (Commae preceding attributes may be omitted.)
%
% \para{Optional attributes}
\vspace*{-8pt}
\begin{description}
\item[{\tt dimen} $n$]\hspace*{0pt}\\
especifica a dimensão de $n$-tuplas das quais o conjunto é consistido;
\item[{\tt within} {\it expressão}]\hspace*{0pt}\\
especifica um superconjunto que restringe ao conjunto ou a todos seus
membros (conjuntos elementares) a estarem incluídos naquele superconjunto;
\item[{\tt:=} {\it expressão}]\hspace*{0pt}\\
especifica um conjunto elementar atribuído ao conjunto ou aos seus membros;
\item[{\tt default} {\it expressão}]\hspace*{0pt}\\
especifica um conjunto elementar atribuído ao conjunto ou aos seus membros
sempre que não há dados apropriados disponíveis na seção de dados.
\end{description}
% \begin{description}
% \item[{\tt dimen} $n$]\hspace*{0pt}\\
% specifies the dimension of $n$-tuples which the set consists of;
% \item[{\tt within} {\it expression}]\hspace*{0pt}\\
% specifies a superset which restricts the set or all its members
% (elemental sets) to be within that superset;
% \item[{\tt:=} {\it expression}]\hspace*{0pt}\\
% specifies an elemental set assigned to the set or its members;
% \item[{\tt default} {\it expression}]\hspace*{0pt}\\
% specifies an elemental set assigned to the set or its members whenever
% no appropriate data are available in the data section.
% \end{description}
\vspace*{-8pt}
\para{Exemplos}
% \para{Examples}
\begin{verbatim}
set nos;
set arcos within nos cross nos;
set passo{s in 1..maxiter} dimen 2 := if s = 1 then arcos else passo[s-1]
union setof{k in nos, (i,k) in passo[s-1], (k,j) in passo[s-1]}(i,j);
set A{i in I, j in J}, within B[i+1] cross C[j-1], within D diff E,
default {('abc',123), (321,'cba')};
\end{verbatim}
% \begin{verbatim}
% set nodes;
% set arcs within nodes cross nodes;
% set step{s in 1..maxiter} dimen 2 := if s = 1 then arcs else step[s-1]
% union setof{k in nodes, (i,k) in step[s-1], (k,j) in step[s-1]}(i,j);
% set A{i in I, j in J}, within B[i+1] cross C[j-1], within D diff E,
% default {('abc',123), (321,'cba')};
% \end{verbatim}
A sentença set declara um conjunto. Se o domínio do subíndice não é
especificado, o conjunto é um conjunto simples, caso contrário será
uma matriz de conjuntos elementares.
O atributo {\tt dimen} especifica a dimensão de $n$-tuplas da qual é
consistida o conjunto (se o conjunto é simples) ou seus membros
(se o conjunto é uma matriz de conjuntos elementares),
em que $n$ deve ser um inteiro de 1 a 20. Pode-se especificar
no máximo um atributo {\tt dimen}. Se o atributo {\tt dimen} não é
especificado, a dimensão das $n$-tuplas é implicitamente determinada
por outros atributos (por exemplo, se há uma expressão que segue
{\tt:=} ou a palavra-chave {\tt default}, usa-se a dimensão das $n$-tuplas
do conjunto elementar correspondente).
Se nenhuma informação de dimensão é fornecida, assume-se
{\tt dimen 1}.
O atributo {\tt within} especifica uma expressão de conjunto cujo
valor resultante é um superconjunto usado para restringir o conjunto
(se o conjunto é simples) ou seus membros (se o conjunto é uma matriz
de conjuntos elementares) a estar incluído naquele superconjunto.
Um número arbitrário de atributos {\tt within} podem ser especificados
na mesma sentença set.
O atributo de atribuição ({\tt:=}) especifica uma expressão de conjunto
usada para avaliar conjunto(s) \linebreak elementar(es) atribuído(s) ao conjunto
(se o conjunto é simples) ou seus membros (se o conjunto é uma matriz
de conjuntos elementares). Se o atributo de atribuição é especificado,
o conjunto é {\it calculável}, portanto, não há a necessidade de fornecer
dados na seção de dados. Se o atributo de atribuição não é especificado,
deve-se fornecer os dados na seção de dados. Pode-se especificar no
máximo um atributo de atribuição ou {\tt default} para o mesmo conjunto.
O atributo {\tt default} especifica uma expressão de conjunto usado para
avaliar conjunto(s) \linebreak elementar(es) atribuído(s) ao conjunto
(se o conjunto é simples) ou seus membros (se o conjunto é uma matriz
de conjuntos elementares) sempre que não houver dados apropriados
disponíveis na seção de dados. Se não se especifica nem o atributo de
atribuição nem o atributo {\tt default}, a falta de dados causará um erro.
% The set statement declares a set. If the subscript domain is not
% specified, the set is a simple set, otherwise it is an array of
% elemental sets.
%
% The {\tt dimen} attribute specifies the dimension of $n$-tuples, which
% the set (if it is a simple set) or its members (if the set is an array
% of elemental sets) consist of, where $n$ should be an unsigned integer
% from 1 to 20. At most one {\tt dimen} attribute can be specified. If
% the {\tt dimen} attribute is not specified, the dimension of $n$-tuples
% is implicitly determined by other attributes (for example, if there is
% a set expression that follows {\tt:=} or the keyword {\tt default}, the
% dimension of $n$-tuples of corresponding elemental set is used).
% If no dimension information is available, {\tt dimen 1} is assumed.
%
% The {\tt within} attribute specifies a set expression whose resultant
% value is a superset used to restrict the set (if it is a simple set) or
% its members (if the set is an array of elemental sets) to be within
% that superset. Arbitrary number of {\tt within} attributes may be
% specified in the same set statement.
%
% The assign ({\tt:=}) attribute specifies a set expression used to
% evaluate elemental set(s) assigned to the set (if it is a simple set)
% or its members (if the set is an array of elemental sets). If the
% assign attribute is specified, the set is {\it computable} and
% therefore needs no data to be provided in the data section. If the
% assign attribute is not specified, the set should be provided with data
% in the data section. At most one assign or default attribute can be
% specified for the same set.
%
% The {\tt default} attribute specifies a set expression used to evaluate
% elemental set(s) assigned to the set (if it is a simple set) or its
% members (if the set is an array of elemental sets) whenever
% no appropriate data are available in the data section. If neither
% assign nor default attribute is specified, missing data will cause an
% error.
\newpage
\section{Sentença parameter}
\noindent
\framebox[468pt][l]{
\parbox[c][24pt]{468pt}{
\hspace{6pt} {\tt param} {\it nome} {\it alias} {\it domínio} {\tt,}
{\it attrib} {\tt,} \dots {\tt,} {\it attrib} {\tt;}
}}
% \noindent
% \framebox[468pt][l]{
% \parbox[c][24pt]{468pt}{
% \hspace{6pt} {\tt param} {\it name} {\it alias} {\it domain} {\tt,}
% {\it attrib} {\tt,} \dots {\tt,} {\it attrib} {\tt;}
% }}
\medskip
\noindent
{\it nome} é um nome simbólico do parâmetro;
\noindent
{\it alias} é um literal de cadeia opcional que especifica um pseudônimo
para o parâmetro;
\noindent
{\it domínio} é uma expressão indexante opcional que especifica o domínio
do subíndice do parâmetro;
\noindent
{\it atributo}, \dots, {\it atributo} são atributos opcionais do parâmetro
(as vírgulas que precedem os atributos podem ser omitidas.)
\para{Atributos opcionais}
% \noindent
% {\it name} is a symbolic name of the parameter;
%
% \noindent
% {\it alias} is an optional string literal, which specifies an alias of
% the parameter;
%
% \noindent
% {\it domain} is an optional indexing expression, which specifies
% a subscript domain of the parameter;
%
% \noindent
% {\it attrib}, \dots, {\it attrib} are optional attributes of the
% parameter. (Commae preceding attributes may be omitted.)
%
% \para{Optional attributes}
\vspace*{-8pt}
\begin{description}
\item[{\tt integer}]\hspace*{0pt}\\
especifica que o parâmetro é inteiro;
\item[{\tt binary}]\hspace*{0pt}\\
especifica que o parâmetro é binário;
\item[{\tt symbolic}]\hspace*{0pt}\\
especifica que o parâmetro é simbólico;
\item[{\it expressão de relação}]\hspace*{0pt}\\
(onde {\it relação} é algum de: {\tt<}, {\tt<=}, {\tt=}, {\tt==},
{\tt>=}, {\tt>}, {\tt<>}, {\tt!=})\\
especifica uma condição que restringe o parâmetro ou seus membros a
satisfazer aquela condição;
\item[{\tt in} {\it expressão}]\hspace*{0pt}\\
especifica um superconjunto que restringe o parâmetro ou seus membros
a estarem inseridos naquele superconjunto;
\item[{\tt:=} {\it expressão}]\hspace*{0pt}\\
especifica um valor atribuído ao parâmetro ou a seus membros;
\item[{\tt default} {\it expressão}]\hspace*{0pt}\\
especifica um valor atribuído ao parâmetro ou aos seus membros sempre
que não houverem dados disponíveis na seção de dados.
\end{description}
% \begin{description}
% \item[{\tt integer}]\hspace*{0pt}\\
% specifies that the parameter is integer;
% \item[{\tt binary}]\hspace*{0pt}\\
% specifies that the parameter is binary;
% \item[{\tt symbolic}]\hspace*{0pt}\\
% specifies that the parameter is symbolic;
% \item[{\it relation expression}]\hspace*{0pt}\\
% (where {\it relation} is one of: {\tt<}, {\tt<=}, {\tt=}, {\tt==},
% {\tt>=}, {\tt>}, {\tt<>}, {\tt!=})\\
% specifies a condition that restricts the parameter or its members to
% satisfy that condition;
% \item[{\tt in} {\it expression}]\hspace*{0pt}\\
% specifies a superset that restricts the parameter or its members to be
% in that superset;
% \item[{\tt:=} {\it expression}]\hspace*{0pt}\\
% specifies a value assigned to the parameter or its members;
% \item[{\tt default} {\it expression}]\hspace*{0pt}\\
% specifies a value assigned to the parameter or its members whenever
% no appropriate data are available in the data section.
% \end{description}
\vspace*{-8pt}
\para{Exemplos}
% \para{Examples}
\begin{verbatim}
param unidades{insumo, produto} >= 0;
param lucro{produto, 1..T+1};
param N := 20 integer >= 0 <= 100;
param combinacao 'n escolhe k' {n in 0..N, k in 0..n} :=
if k = 0 or k = n then 1 else combinacao[n-1,k-1] + combinacao[n-1,k];
param p{i in I, j in J}, integer, >= 0, <= i+j, in A[i] symdiff B[j],
in C[i,j], default 0.5 * (i + j);
param mes symbolic default 'Mai' in {'Mar', 'Abr', 'Mai'};
\end{verbatim}
% \begin{verbatim}
% param units{raw, prd} >= 0;
% param profit{prd, 1..T+1};
% param N := 20 integer >= 0 <= 100;
% param comb 'n choose k' {n in 0..N, k in 0..n} :=
% if k = 0 or k = n then 1 else comb[n-1,k-1] + comb[n-1,k];
% param p{i in I, j in J}, integer, >= 0, <= i+j, in A[i] symdiff B[j],
% in C[i,j], default 0.5 * (i + j);
% param month symbolic default 'May' in {'Mar', 'Apr', 'May'};
% \end{verbatim}
A sentença parameter declara um parâmetro. Se o domínio de subíndice não
é especificado, o parâmetro é simples (escalar), caso contrário,
é uma matriz $n$-dimensional.
Os atributos de tipo {\tt integer}, {\tt binary} e {\tt symbolic}
qualificam os tipos de valores que podem ser atribuídos ao parâmetro, conforme
demonstrado:
% The parameter statement declares a parameter. If a subscript domain is
% not specified, the parameter is a simple (scalar) parameter, otherwise
% it is a $n$-dimensional array.
%
% The type attributes {\tt integer}, {\tt binary}, and {\tt symbolic}
% qualify the type of values that can be assigned to the parameter as
% shown below:
\noindent\hfil
\begin{tabular}{@{}ll@{}}
Tipo de atributo&Valores atribuídos\\
\hline
(não especificado)&Qualquer valor numérico\\
{\tt integer}&Apenas valores numéricos inteiros\\
{\tt binary}&Tanto 0 quanto 1\\
{\tt symbolic}&Qualquer valor numérico e simbólico\\
\end{tabular}
% \noindent\hfil
% \begin{tabular}{@{}ll@{}}
% Type attribute&Assigned values\\
% \hline
% (not specified)&Any numeric values\\
% {\tt integer}&Only integer numeric values\\
% {\tt binary}&Either 0 or 1\\
% {\tt symbolic}&Any numeric and symbolic values\\
% \end{tabular}
O atributo {\tt symbolic} não pode ser especificado juntamente com outros tipos
de atributos. Uma vez especificado, ele deve preceder todos os outros atributos.
O atributo de condição especifica uma condição opcional que restringe
os valores atribuídos ao parâmetro para satisfazer aquela condição.
Este atributo tem as seguintes formas sintáticas:
% The {\tt symbolic} attribute cannot be specified along with other type
% attributes. Being specified it should precede all other attributes.
%
% The condition attribute specifies an optional condition that restricts
% values assigned to the parameter to satisfy that condition. This
% attribute has the following syntactic forms:
\begin{tabular}{@{}ll@{}}
{\tt<} $v$&verifica se $x<v$\\
{\tt<=} $v$&verifica se $x\leq v$\\
{\tt=} $v$, {\tt==} $v$&verifica se $x=v$\\
{\tt>=} $v$&verifica se $x\geq v$\\
{\tt>} $v$&verifica se $x\geq v$\\
{\tt<>} $v$, {\tt!=} $v$&verifica se $x\neq v$\\
\end{tabular}
% \begin{tabular}{@{}ll@{}}
% {\tt<} $v$&check for $x<v$\\
% {\tt<=} $v$&check for $x\leq v$\\
% {\tt=} $v$, {\tt==} $v$&check for $x=v$\\
% {\tt>=} $v$&check for $x\geq v$\\
% {\tt>} $v$&check for $x\geq v$\\
% {\tt<>} $v$, {\tt!=} $v$&check for $x\neq v$\\
% \end{tabular}
\noindent onde $x$ é um valor atribuído ao parâmetro, $v$ é o
valor resultante de uma expressão numérica ou simbólica especificado
no atributo de condição. Um número arbitrário de atributos de condição
pode ser especificado para o mesmo parâmetro. Se, durante a avaliação do
modelo, um valor atribuído ao parâmetro viola pelo menos uma das
condições especificadas, ocorrerá um erro. (Note que valores simbólicos
são ordenados de forma lexicográfica e qualquer valor numérico precede
qualquer valor simbólico.)
O atributo {\tt in} é similar ao atributo de condição e especifica
uma expressão de conjunto cujo valor resultante é um superconjunto usado
para restringir valores numéricos ou simbólicos atribuídos ao parâmetro
a estarem incluídos naquele superconjunto. Pode-se especificar um número
arbitrário de atributos {\tt in} para o mesmo parâmetro. Se, durante a avaliação do
modelo, o valor atribuído ao parâmetro não pertence a pelo menos um dos
superconjuntos especificados, ocorrerá um erro.
O atributo de atribuição ({\tt:=}) especifica uma expressão numérica
ou simbólica usada para \linebreak computar um valor atribuído ao parâmetro
(se é um parâmetro simples) ou seus membros (se o parâmetro é uma matriz).
Se o atributo de atribuição é especificado,
o parâmetro é {\it calculável}, \linebreak portanto, não há a necessidade de fornecer
dados na seção de dados. Se o atributo de atribuição não é especificado,
deve-se fornecer os dados para o parâmetro na seção de dados. Pode-se especificar no
máximo um atributo de atribuição ou {\tt default} para o mesmo parâmetro.
O atributo {\tt default} especifica uma expressão numérica ou simbólica
usada para computar um valor atribuído ao parâmetro ou seus membros
sempre que não houver dados apropriados disponíveis na seção de dados.
Se não se especifica nem o atributo de atribuição nem o atributo
{\tt default}, a falta de dados causará um erro.
% \noindent where $x$ is a value assigned to the parameter, $v$ is the
% resultant value of a numeric or symbolic expression specified in the
% condition attribute. Arbitrary number of condition attributes can be
% specified for the same parameter. If a value being assigned to the
% parameter during model evaluation violates at least one of specified
% conditions, an error is raised. (Note that symbolic values are ordered
% lexicographically, and any numeric value precedes any symbolic value.)
%
% The {\tt in} attribute is similar to the condition attribute and
% specifies a set expression whose resultant value is a superset used to
% restrict numeric or symbolic values assigned to the parameter to be in
% that superset. Arbitrary number of the {\tt in} attributes can be
% specified for the same parameter. If a value being assigned to the
% parameter during model evaluation is not in at least one of specified
% supersets, an error is raised.
%
% The assign ({\tt:=}) attribute specifies a numeric or symbolic
% expression used to compute a value assigned to the parameter (if it is
% a simple parameter) or its member (if the parameter is an array). If
% the assign attribute is specified, the parameter is {\it computable}
% and therefore needs no data to be provided in the data section. If the
% assign attribute is not specified, the parameter should be provided
% with data in the data section. At most one assign or {\tt default}
% attribute can be specified for the same parameter.
%
% The {\tt default} attribute specifies a numeric or symbolic expression
% used to compute a value assigned to the parameter or its member
% whenever no appropriate data are available in the data section. If
% neither assign nor {\tt default} attribute is specified, missing data
% will cause an error.
\newpage
\section{Sentença variable}
\noindent
\framebox[468pt][l]{
\parbox[c][24pt]{468pt}{
\hspace{6pt} {\tt var} {\it nome} {\it alias} {\it domínio} {\tt,}
{\it atrib} {\tt,} \dots {\tt,} {\it atrib} {\tt;}
}}
\medskip
\noindent
{\it nome} é um nome simbólico da variável;
\noindent
{\it alias} é um literal de cadeia opcional que especifica um pseudônimo
para a variável;
\noindent
{\it domínio} é uma expressão indexante opcional que especifica o domínio
do subíndice da variável;
\noindent
{\it atrib}, \dots, {\it atrib} são atributos opcionais da variável
(as vírgulas que precedem os atributos podem ser omitidas.)
\para{Atributos opcionais}
\vspace*{-8pt}
\begin{description}
\item[{\tt integer}]\hspace*{0pt}\\
restringe a variável a ser inteira;
\item[{\tt binary}]\hspace*{0pt}\\
restringe a variável a ser binária;
\item[{\tt>=} {\it expressão}]\hspace*{0pt}\\
especifica um limite inferior para a variável;
\item[{\tt<=} {\it expressão}]\hspace*{0pt}\\
especifica um limite superior para a variável;
\item[{\tt=} {\it expressão}]\hspace*{0pt}\\
especifica um valor fixo para a variável;
\end{description}
% \noindent
% \framebox[468pt][l]{
% \parbox[c][24pt]{468pt}{
% \hspace{6pt} {\tt var} {\it name} {\it alias} {\it domain} {\tt,}
% {\it attrib} {\tt,} \dots {\tt,} {\it attrib} {\tt;}
% }}
%
% \medskip
%
% \noindent
% {\it name} is a symbolic name of the variable;
%
% \noindent
% {\it alias} is an optional string literal, which specifies an alias of
% the variable;
%
% \noindent
% {\it domain} is an optional indexing expression, which specifies
% a subscript domain of the variable;
%
% \noindent
% {\it attrib}, \dots, {\it attrib} are optional attributes of the
% variable. (Commae preceding attributes may be omitted.)
%
% \para{Optional attributes}
%
% \vspace*{-8pt}
%
% \begin{description}
% \item[{\tt integer}]\hspace*{0pt}\\
% restricts the variable to be integer;
% \item[{\tt binary}]\hspace*{0pt}\\
% restricts the variable to be binary;
% \item[{\tt>=} {\it expression}]\hspace*{0pt}\\
% specifies an lower bound of the variable;
% \item[{\tt<=} {\it expression}]\hspace*{0pt}\\
% specifies an upper bound of the variable;
% \item[{\tt=} {\it expression}]\hspace*{0pt}\\
% specifies a fixed value of the variable;
% \end{description}
\vspace*{-8pt}
\para{Exemplos}
% \para{Examples}
\begin{verbatim}
var x >= 0;
var y{I,J};
var produzir{p in prod}, integer, >= comprometido[p], <= mercado[p];
var armazenar{insumo, 1..T+1} >= 0;
var z{i in I, j in J} >= i+j;
\end{verbatim}
% \begin{verbatim}
% var x >= 0;
% var y{I,J};
% var make{p in prd}, integer, >= commit[p], <= market[p];
% var store{raw, 1..T+1} >= 0;
% var z{i in I, j in J} >= i+j;
% \end{verbatim}
A sentença variable declara uma variável. Se não se especifica o
domínio do subíndice, a variável e uma variável simples (escalar),
caso contrário é uma matriz $n$-dimensional de variáveis elementares.
As variáveis elementares associadas com a variável do modelo
(se é uma variável simples) ou seus membros (se é uma matriz) corresponde
às variáveis na formulação do problema PL/PIM (ver Seção \ref{problem},
página \pageref{problem}). Note que somente variáveis elementares
realmente referenciadas em algumas restrições e/ou objetivos serão
incluídas na instância do problema PL/PIM a ser gerado.
Os atributos de tipo {\tt integer} e {\tt binary} restringem a variável
a ser inteira ou binária, \linebreak respectivamente. Se nenhum atributo de tipo
é especificado, a variável é contínua. Se todas as variáveis no modelo
são contínuas, o problema correspondente é da classe PL. Se há pelo
menos uma variável inteira ou binária, o problema é da classe PIM.
\newpage
O atributo de limite inferior ({\tt>=}) especifica uma expressão numérica
para calcular um limite inferior da variável. No máximo um limite inferior
pode ser especificado. Por padrão, todas as variáveis (exceto as binárias)
não tem limite inferior, assim, se há a necessidade de uma variável ser
não-negativa, seu limite inferior zero deve ser explicitamente especificado.
O atributo de limite superior ({\tt<=}) especifica uma expressão numérica
para calcular um limite superior da variável. No máximo um limite superior
pode ser especificado.
O atributo de valor fixo ({\tt=}) especifica uma expressão numérica para
calcular um valor no qual a variável é fixada. Este atributo não pode
ser especificado junto com os atributos de limite.
% The variable statement declares a variable. If a subscript domain is
% not specified, the variable is a simple (scalar) variable, otherwise it
% is a $n$-dimensional array of elemental variables.
%
% Elemental variable(s) associated with the model variable (if it is a
% simple variable) or its members (if it is an array) correspond to the
% variables in the LP/MIP problem formulation (see Section \ref{problem},
% page \pageref{problem}). Note that only elemental variables actually
% referenced in some constraints and/or objectives are included in the
% LP/MIP problem instance to be generated.
%
% The type attributes {\tt integer} and {\tt binary} restrict the
% variable to be integer or binary, respectively. If no type attribute is
% specified, the variable is continuous. If all variables in the model
% are continuous, the corresponding problem is of LP class. If there is
% at least one integer or binary variable, the problem is of MIP class.
%
% The lower bound ({\tt>=}) attribute specifies a numeric expression for
% computing an lower bound of the variable. At most one lower bound can
% be specified. By default all variables (except binary ones) have no
% lower bound, so if a variable is required to be non-negative, its zero
% lower bound should be explicitly specified.
%
% The upper bound ({\tt<=}) attribute specifies a numeric expression for
% computing an upper bound of the variable. At most one upper bound
% attribute can be specified.
%
% The fixed value ({\tt=}) attribute specifies a numeric expression for
% computing a value, at which the variable is fixed. This attribute
% cannot be specified along with the bound attributes.
\section{Sentença constraint}
\noindent
\framebox[468pt][l]{
\parbox[c][106pt]{468pt}{
\hspace{6pt} {\tt s.t.} {\it nome} {\it alias} {\it domínio} {\tt:}
{\it expressão} {\tt,} {\tt=} {\it expressão} {\tt;}
\medskip
\hspace{6pt} {\tt s.t.} {\it nome} {\it alias} {\it domínio} {\tt:}
{\it expressão} {\tt,} {\tt<=} {\it expressão} {\tt;}
\medskip
\hspace{6pt} {\tt s.t.} {\it nome} {\it alias} {\it domínio} {\tt:}
{\it expressão} {\tt,} {\tt>=} {\it expressão} {\tt;}
\medskip
\hspace{6pt} {\tt s.t.} {\it nome} {\it alias} {\it domínio} {\tt:}
{\it expressão} {\tt,} {\tt<=} {\it expressão} {\tt,} {\tt<=}
{\it expressão} {\tt;}
\medskip
\hspace{6pt} {\tt s.t.} {\it nome} {\it alias} {\it domínio} {\tt:}
{\it expressão} {\tt,} {\tt>=} {\it expressão} {\tt,} {\tt>=}
{\it expressão} {\tt;}
}}
\medskip
\noindent
{\it nome} é um nome simbólico da restrição;
\noindent
{\it alias} é um literal de cadeia opcional que especifica um pseudônimo
da restrição;
\noindent
{\it domínio} é uma expressão indexante opcional, que especifica
o domínio do subíndice da restrição;
\noindent
{\it expressão} é uma expressão linear usada para calcular um componente
da restrição (as vírgulas que precedem os atributos podem ser omitidas).
\noindent
(A palavra-chave {\tt s.t.} pode ser escrita como {\tt subject to}, como
{\tt subj to} ou pode ser omitido por completo).
% \noindent
% \framebox[468pt][l]{
% \parbox[c][106pt]{468pt}{
% \hspace{6pt} {\tt s.t.} {\it name} {\it alias} {\it domain} {\tt:}
% {\it expression} {\tt,} {\tt=} {\it expression} {\tt;}
%
% \medskip
%
% \hspace{6pt} {\tt s.t.} {\it name} {\it alias} {\it domain} {\tt:}
% {\it expression} {\tt,} {\tt<=} {\it expression} {\tt;}
%
% \medskip
%
% \hspace{6pt} {\tt s.t.} {\it name} {\it alias} {\it domain} {\tt:}
% {\it expression} {\tt,} {\tt>=} {\it expression} {\tt;}
%
% \medskip
%
% \hspace{6pt} {\tt s.t.} {\it name} {\it alias} {\it domain} {\tt:}
% {\it expression} {\tt,} {\tt<=} {\it expression} {\tt,} {\tt<=}
% {\it expression} {\tt;}
%
% \medskip
%
% \hspace{6pt} {\tt s.t.} {\it name} {\it alias} {\it domain} {\tt:}
% {\it expression} {\tt,} {\tt>=} {\it expression} {\tt,} {\tt>=}
% {\it expression} {\tt;}
% }}
%
% \medskip
%
% \noindent
% {\it name} is a symbolic name of the constraint;
%
% \noindent
% {\it alias} is an optional string literal, which specifies an alias of
% the constraint;
%
% \noindent
% {\it domain} is an optional indexing expression, which specifies
% a subscript domain of the constraint;
%
% \noindent
% {\it expression} is a linear expression used to compute a component of
% the constraint. (Commae following expressions may be omitted.)
%
% \noindent
% (The keyword {\tt s.t.} may be written as {\tt subject to} or as
% {\tt subj to}, or may be omitted at all.)
\para{Exemplos}
% \para{Examples}
\begin{verbatim}
s.t. r: x + y + z, >= 0, <= 1;
limite{t in 1..T}: sum{j in produto} produzir[j,t] <= max_prod;
subject to balanco{i in insumo, t in 1..T}:
estoque[i,t+1] = estoque[i,t] - sum{j in produto} unidades[i,j] * produzir[j,t];
subject to rlim 'limite tempo-regular' {t in tempo}:
sum{p in produto} pt[p] * rprod[p,t] <= 1.3 * dpp[t] * equipes[t];
\end{verbatim}
% \begin{verbatim}
% s.t. r: x + y + z, >= 0, <= 1;
% limit{t in 1..T}: sum{j in prd} make[j,t] <= max_prd;
% subject to balance{i in raw, t in 1..T}:
% store[i,t+1] = store[i,t] - sum{j in prd} units[i,j] * make[j,t];
% subject to rlim 'regular-time limit' {t in time}:
% sum{p in prd} pt[p] * rprd[p,t] <= 1.3 * dpp[t] * crews[t];
% \end{verbatim}
A sentença de restrição declara uma restrição. Se o domínio do subíndice
não é especificado, a restrição é uma restrição simples (escalar),
caso contrário, é uma matriz $n$-dimensional de restrições elementares.
Restrições elementares associadas com a restrição do modelo (se é
uma restrição simples) ou seus membros (se é uma matriz) correspondem
a restrições lineares na formulação do problema de PL/PIM (ver
Seção \ref{problem}, página \pageref{problem}).
Se a restrição possui a forma de igualdade ou desigualdade simples, i.e.,
inclui duas expressões, uma segue depois dos dois pontos e a outra
segue depois do sinal de relação {\tt=}, {\tt<=} ou {\tt>=}, \linebreak ambas
expressões na sentença podem ser expressões lineares. Se a restrição
possui a forma de uma \linebreak desigualdade dupla, i.e., inclui três expressões,
a expressão do meio pode ser uma expressão linear, enquanto a da
esquerda e a da direita podem ser apenas expressões numéricas.
Gerar o modelo é, a grosso modo, gerar suas restrições, que são sempre
avaliadas para todo domínio do subíndice. Avaliar as restrições,
por sua vez, leva a avaliação de outros objetos de modelo tais como
conjuntos, parâmetros e variáveis.
A construção de uma restrição linear incluída na instância do problema,
que corresponde a uma restrição elementar particular, é realizada
como segue.
% The constraint statement declares a constraint. If a subscript domain
% is not specified, the\linebreak constraint is a simple (scalar)
% constraint, otherwise it is a $n$-dimensional array of elemental
% constraints.
%
% Elemental constraint(s) associated with the model constraint (if it is
% a simple constraint) or its members (if it is an array) correspond to
% the linear constraints in the LP/MIP problem formulation (see
% Section \ref{problem}, page \pageref{problem}).
%
% If the constraint has the form of equality or single inequality, i.e.
% includes two expressions, one of which follows the colon and other
% follows the relation sign {\tt=}, {\tt<=}, or {\tt>=}, both expressions
% in the statement can be linear expressions. If the constraint has the
% form of double inequality,\linebreak i.e. includes three expressions,
% the middle expression can be a linear expression while the leftmost and
% rightmost ones can be only numeric expressions.
%
% Generating the model is, roughly speaking, generating its constraints,
% which are always evaluated for the entire subscript domain. Evaluation
% of the constraints leads, in turn, to evaluation of other model objects
% such as sets, parameters, and variables.
%
% Constructing an actual linear constraint included in the problem
% instance, which (constraint) corresponds to a particular elemental
% constraint, is performed as follows.
Se a restrição possui a forma de igualdade ou desigualdade simples,
a avaliação de ambas \linebreak expressões lineares resultam em duas formas lineares:
$$\begin{array}{r@{\ }c@{\ }r@{\ }c@{\ }r@{\ }c@{\ }r@{\ }c@{\ }r}
f&=&a_1x_1&+&a_2x_2&+\dots+&a_nx_n&+&a_0,\\
g&=&b_1x_1&+&b_2x_2&+\dots+&b_nx_n&+&b_0,\\
\end{array}$$
onde $x_1$, $x_2$, \dots, $x_n$ são variáveis elementares; $a_1$, $a_2$,
\dots, $a_n$, $b_1$, $b_2$, \dots, $b_n$ são coeficientes numéricos;
$a_0$ e $b_0$ são termos constantes. Em seguida, todos os termos lineares
de $f$ e $g$ são levados ao lado esquerdo, enquanto que os termos constantes
são levados ao lado direito, resultando na restrição elementar
final na forma padrão:
$$(a_1-b_1)x_1+(a_2-b_2)x_2+\dots+(a_n-b_n)x_n\left\{
\begin{array}{@{}c@{}}=\\\leq\\\geq\\\end{array}\right\}b_0-a_0.$$
Se a restrição possui a forma de desigualdade dupla, a avaliação da
expressão linear do meio resulta na seguinte forma linear:
$$f=a_1x_1+a_2x_2+\dots+a_nx_n+a_0,$$
e a avaliação das expressões numéricas da esquerda e da direita dão
dois valores numéricos $l$ e $u$, respectivamente. Logo,
o termo constante da forma linear é levado tanto à esquerda como
à direita para gerar a restrição elementar final na forma padrão:
$$l-a_0\leq a_1x_1+a_2x_2+\dots+a_nx_n\leq u-a_0.$$
% If the constraint has the form of equality or single inequality,
% evaluation of both linear expressions gives two resultant linear forms:
% $$\begin{array}{r@{\ }c@{\ }r@{\ }c@{\ }r@{\ }c@{\ }r@{\ }c@{\ }r}
% f&=&a_1x_1&+&a_2x_2&+\dots+&a_nx_n&+&a_0,\\
% g&=&b_1x_1&+&a_2x_2&+\dots+&a_nx_n&+&b_0,\\
% \end{array}$$
% where $x_1$, $x_2$, \dots, $x_n$ are elemental variables; $a_1$, $a_2$,
% \dots, $a_n$, $b_1$, $b_2$, \dots, $b_n$ are numeric coefficients;
% $a_0$ and $b_0$ are constant terms. Then all linear terms of $f$ and
% $g$ are carried to the left-hand side, and the constant terms are
% carried to the right-hand side, that gives the final elemental
% constraint in the standard form:
% $$(a_1-b_1)x_1+(a_2-b_2)x_2+\dots+(a_n-b_n)x_n\left\{
% \begin{array}{@{}c@{}}=\\\leq\\\geq\\\end{array}\right\}b_0-a_0.$$
%
% If the constraint has the form of double inequality, evaluation of the
% middle linear expression gives the resultant linear form:
% $$f=a_1x_1+a_2x_2+\dots+a_nx_n+a_0,$$
% and evaluation of the leftmost and rightmost numeric expressions gives
% two numeric values $l$ and $u$, respectively. Then the constant term of
% the linear form is carried to both left-hand and right-handsides that
% gives the final elemental constraint in the standard form:
% $$l-a_0\leq a_1x_1+a_2x_2+\dots+a_nx_n\leq u-a_0.$$
\section{Sentença objective}
\noindent
\framebox[468pt][l]{
\parbox[c][44pt]{468pt}{
\hspace{6pt} {\tt minimize} {\it nome} {\it alias} {\it domínio} {\tt:}
{\it expressão} {\tt;}
\medskip
\hspace{6pt} {\tt maximize} {\it nome} {\it alias} {\it domínio} {\tt:}
{\it expressão} {\tt;}
}}
\medskip
\noindent
{\it nome} é um nome simbólico do objetivo;
\noindent
{\it alias} é uma literal de cadeia opcional que especifica um
pseudônimo do objetivo;
\noindent
{\it domínio} é uma expressão indexante opcional que especifica
um domínio do subíndice do objetivo;
\noindent
{\it expressão} é uma expressão linear usada pra calcular a forma
linear do objetivo.
% \noindent
% \framebox[468pt][l]{
% \parbox[c][44pt]{468pt}{
% \hspace{6pt} {\tt minimize} {\it name} {\it alias} {\it domain} {\tt:}
% {\it expression} {\tt;}
%
% \medskip
%
% \hspace{6pt} {\tt maximize} {\it name} {\it alias} {\it domain} {\tt:}
% {\it expression} {\tt;}
% }}
%
% \medskip
%
% \noindent
% {\it name} is a symbolic name of the objective;
%
% \noindent
% {\it alias} is an optional string literal, which specifies an alias of
% the objective;
%
% \noindent
% {\it domain} is an optional indexing expression, which specifies
% a subscript domain of the objective;
%
% \noindent
% {\it expression} is a linear expression used to compute the linear form
% of the objective.
\newpage
\para{Exemplos}
% \para{Examples}
\begin{verbatim}
minimize obj: x + 1.5 * (y + z);
maximize lucro_total: sum{p in produto} lucro[p] * produzir[p];
\end{verbatim}
% \begin{verbatim}
% minimize obj: x + 1.5 * (y + z);
% maximize total_profit: sum{p in prd} profit[p] * make[p];
% \end{verbatim}
A sentença objective declara um objetivo. Se o domínio do subíndice
não é especificado, o objetivo é um objetivo simples (escalar). Caso contrário,
é uma matriz $n$-dimensional de objetivos elementares.
Objetivos elementares associados com o objetivo do modelo (se é um
objetivo simples) ou seus membros (se é uma matriz) correspondem
a restrições lineares genéricas na formulação do problema PL/PIM
(ver Seção \ref{problem}, página \pageref{problem}). No entanto,
diferentemente das restrições, estas formas lineares são livres
(ilimitadas).
A construção de uma forma linear incluída na instância do problema,
a qual corresponde a uma restrição elementar particular,
é realizada como segue. A expressão linear especificada da na
sentença objective é avaliada para resultar na seguinte forma linear:
$$f=a_1x_1+a_2x_2+\dots+a_nx_n+a_0,$$
onde $x_1$, $x_2$, \dots, $x_n$ são variáveis elementares; $a_1$, $a_2$,
\dots, $a_n$ são coeficientes numéricos; $a_0$ é o termo constante. Logo,
a forma linear é usada para construir a restrição final elementar na
forma padrão:
$$-\infty<a_1x_1+a_2x_2+\dots+a_nx_n+a_0<+\infty.$$
Como via de regra, a descrição do modelo contém apenas uma sentença objective
que define a função objetivo usada na instância do problema.
No entanto, é permitido declarar uma quantidade arbitrária de objetivos.
Neste caso, a função objetivo real será o primeiro objetivo
encontrado na descrição do modelo. Outros objetivos também estão
incluídos na instância do problema, mas eles não afetam a função
objetivo.
% The objective statement declares an objective. If a subscript domain is
% not specified, the objective is a simple (scalar) objective. Otherwise
% it is a $n$-dimensional array of elemental objectives.
%
% Elemental objective(s) associated with the model objective (if it is a
% simple objective) or its members (if it is an array) correspond to
% general linear constraints in the LP/MIP problem formulation (see
% Section \ref{problem}, page \pageref{problem}). However, unlike
% constraints the corresponding linear forms are free (unbounded).
%
% Constructing an actual linear constraint included in the problem
% instance, which (constraint) corresponds to a particular elemental
% constraint, is performed as follows. The linear expression specified in
% the objective statement is evaluated that, gives the resultant linear
% form:
% $$f=a_1x_1+a_2x_2+\dots+a_nx_n+a_0,$$
% where $x_1$, $x_2$, \dots, $x_n$ are elemental variables; $a_1$, $a_2$,
% \dots, $a_n$ are numeric coefficients; $a_0$ is the constant term. Then
% the linear form is used to construct the final elemental constraint in
% the standard form:
% $$-\infty<a_1x_1+a_2x_2+\dots+a_nx_n+a_0<+\infty.$$
%
% As a rule the model description contains only one objective statement
% that defines the objective function used in the problem instance.
% However, it is allowed to declare arbitrary number of objectives, in
% which case the actual objective function is the first objective
% encountered in the model description. Other objectives are also
% included in the problem instance, but they do not affect the objective
% function.
\section{Sentença solve}
\noindent
\framebox[468pt][l]{
\parbox[c][24pt]{468pt}{
\hspace{6pt} {\tt solve} {\tt;}
}}
\medskip
A sentença solve é opcional e pode ser usada apenas uma vez.
Se a sentença solve não é usada, ela é assumida ao final da seção de modelo.
A sentença solve provoca que o modelo seja resolvido, o que significa calcular
os valores numéricos de todas as variáveis do modelo. Isto permite usar
variáveis em sentenças abaixo da sentença solve como se fossem parâmetros
numéricos.
Note que a sentença variable, constraint e objective não podem ser usadas
abaixo da sentença solve, i.e., todos os principais componentes do modelo
devem ser declarados acima da sentença solve.
% The solve statement is optional and can be used only once. If no solve
% statement is used, one is assumed at the end of the model section.
%
% The solve statement causes the model to be solved, that means computing
% numeric values of all model variables. This allows using variables in
% statements below the solve statement in the same way as if they were
% numeric parameters.
%
% Note that the variable, constraint, and objective statements cannot be
% used below the solve statement, i.e. all principal components of the
% model should be declared above the solve statement.
\newpage
\section{Sentença check}
\noindent
\framebox[468pt][l]{
\parbox[c][24pt]{468pt}{
\hspace{6pt} {\tt check} {\it domínio} {\tt:} {\it expressão} {\tt;}
}}
\medskip
\noindent
{\it domínio} é uma expressão indexante opcional que especifica o
domínio do subíndice da sentença check;
\noindent
{\it expressão} é uma expressão lógica que especifica a condição
lógica a ser verificada (os dois pontos que precedem a {\it expressão}
podem ser omitidos).
\para{Exemplos}
\begin{verbatim}
check: x + y <= 1 and x >= 0 and y >= 0;
check sum{i in ORIG} suprimento[i] = sum{j in DEST} demanda[j];
check{i in I, j in 1..10}: S[i,j] in U[i] union V[j];
\end{verbatim}
A sentença check permite a verificação do valor resultante
de uma expressão lógica especificada na sentença. Se o valor
é {\it falso}, um erro é reportado.
Se o domínio do subíndice não é especificado, a verificação é realizada
apenas uma vez. \linebreak Especificar o domínio do subíndice
permite a execução de verificações múltiplas para cada $n$-tupla
no conjunto domínio. Neste último caso, a expressão lógica pode
incluir índices introduzidos na expressão indexante correspondente.
% \noindent
% \framebox[468pt][l]{
% \parbox[c][24pt]{468pt}{
% \hspace{6pt} {\tt check} {\it domain} {\tt:} {\it expression} {\tt;}
% }}
%
% \medskip
%
% \noindent
% {\it domain} is an optional indexing expression, which specifies
% a subscript domain of the check statement;
%
% \noindent
% {\it expression} is an logical expression which specifies the logical
% condition to be checked. (The colon preceding {\it expression} may be
% omitted.)
%
% \para{Examples}
%
% \begin{verbatim}
% check: x + y <= 1 and x >= 0 and y >= 0;
% check sum{i in ORIG} supply[i] = sum{j in DEST} demand[j];
% check{i in I, j in 1..10}: S[i,j] in U[i] union V[j];
% \end{verbatim}
%
% The check statement allows checking the resultant value of an logical
% expression specified in the statement. If the value is {\it false}, an
% error is reported.
%
% If the subscript domain is not specified, the check is performed only
% once. Specifying the subscript domain allows performing multiple check
% for every $n$-tuple in the domain set. In the latter case the logical
% expression may include dummy indices introduced in corresponding
% indexing expression.
\section{Sentença display}
\noindent
\framebox[468pt][l]{
\parbox[c][24pt]{468pt}{
\hspace{6pt} {\tt display} {\it domínio} {\tt:} {\it item} {\tt,}
\dots {\tt,} {\it item} {\tt;}
}}
\medskip
\noindent
{\it domínio} é uma expressão indexante opcional que especifica
um domínio do subíndice da sentença display;
\noindent
{\it item}, \dots, {\it item} são itens a serem mostrados (os dois pontos
que precedem o primeiro item podem ser omitidos).
\para{Exemplos}
\begin{verbatim}
display: 'x =', x, 'y =', y, 'z =', z;
display sqrt(x ** 2 + y ** 2 + z ** 2);
display{i in I, j in J}: i, j, a[i,j], b[i,j];
\end{verbatim}
A sentença display avalia todos itens especificados na sentença
e escreve seus valores em saída padrão (terminal) em formato de
texto plano.
Se um domínio de subíndice não é especificado, os itens são avaliados e
mostrados apenas uma vez. Ao especificar o domínio do subíndice, itens
são avaliados e mostrados para cada $n$-tupla no conjunto do domínio. No
último caso, os itens podem incluir índices introduzidos na expressão
indexante correspondente.
Um item a ser mostrado pode ser um objeto de modelo (conjunto, parâmetro,
variável, restrição, objetivo) ou uma expressão.
Se um item é um objeto calculável (i.e., um conjunto ou parâmetro com
o atributo de atribuição), o objeto é avaliado por todo domínio
e em seguida, seu conteúdo (i.e., o conteúdo da matriz de objetos) é
mostrado. Caso contrário, se o item não é um objeto calculável, somente seu
seu conteúdo corrente (i.e., os membros realmente gerados durante a
avaliação do modelo) é mostrado.
Se o item é uma expressão, a expressão é avaliada e seu valor
resultante é mostrado.
% \noindent
% \framebox[468pt][l]{
% \parbox[c][24pt]{468pt}{
% \hspace{6pt} {\tt display} {\it domain} {\tt:} {\it item} {\tt,}
% \dots {\tt,} {\it item} {\tt;}
% }}
%
% \medskip
%
% \noindent
% {\it domain} is an optional indexing expression, which specifies
% a subscript domain of the display statement;
%
% \noindent
% {\it item}, \dots, {\it item} are items to be displayed. (The colon
% preceding the first item may be omitted.)
%
% \para{Examples}
%
% \begin{verbatim}
% display: 'x =', x, 'y =', y, 'z =', z;
% display sqrt(x ** 2 + y ** 2 + z ** 2);
% display{i in I, j in J}: i, j, a[i,j], b[i,j];
% \end{verbatim}
%
% The display statement evaluates all items specified in the statement
% and writes their values on the standard output (terminal) in plain text
% format.
%
% If a subscript domain is not specified, items are evaluated and then
% displayed only once. Specifying the subscript domain causes items to be
% evaluated and displayed for every $n$-tuple in the domain set. In the
% latter case items may include dummy indices introduced in corresponding
% indexing expression.
%
% An item to be displayed can be a model object (set, parameter,
% variable, constraint, objective) or an expression.
%
% If the item is a computable object (i.e. a set or parameter provided
% with the assign attribute), the object is evaluated over the entire
% domain and then its content (i.e. the content of the object array) is
% displayed. Otherwise, if the item is not a computable object, only its
% current content (i.e. members actually generated during the model
% evaluation) is displayed.
%
% If the item is an expression, the expression is evaluated and its
% resultant value is displayed.
\section{Sentença printf}
\noindent
\framebox[468pt][l]{
\parbox[c][64pt]{468pt}{
\hspace{6pt} {\tt printf} {\it domínio} {\tt:} {\it formato} {\tt,}
{\it expressão} {\tt,} \dots {\tt,} {\it expressão} {\tt;}
\medskip
\hspace{6pt} {\tt printf} {\it domínio} {\tt:} {\it formato} {\tt,}
{\it expressão} {\tt,} \dots {\tt,} {\it expressão} {\tt>}
{\it nome-do-arquivo} {\tt;}
\medskip
\hspace{6pt} {\tt printf} {\it domínio} {\tt:} {\it formato} {\tt,}
{\it expressão} {\tt,} \dots {\tt,} {\it expressão} {\tt>>}
{\it nome-do-arquivo} {\tt;}
}}
\medskip
\noindent
{\it domínio} é uma expressão indexante opcional que especifica o domínio
do subíndice da sentença printf;
\noindent
{\it formato} é uma expressão simbólica cujo valor especifica uma cadeia de
controle de formato (os dois pontos que precedem a expressão de formato
podem ser omitidos).
\noindent
{\it expressão}, \dots, {\it expressão} são zero ou mais expressões
cujos valores devem ser formatados e impressos. Cada expressão deve
ser de tipo numérico, simbólico ou lógico.
\noindent
{\it nome-do-arquivo} é uma expressão simbólica cujo valor especifica um nome
de um arquivo de texto para onde a saída é redirecionada. O sinal {\tt>}
significa criar um novo aquivo vazio, enquanto o sinal {\tt>>} significa
acrescentar a saída a um arquivo existente. Se o nome do arquivo não é especificado,
a saída é escrita na saída padrão (terminal).
\para{Exemplos}
\begin{verbatim}
printf 'Ola, mundo!\n';
printf: "x = %.3f; y = %.3f; z = %.3f\n", x, y, z > "resultado.txt";
printf{i in I, j in J}: "fluxo de %s para %s eh %d\n", i, j, x[i,j]
>> arquivo_resultado & ".txt";
printf{i in I} 'fluxo total de %s eh %g\n', i, sum{j in J} x[i,j];
printf{k in K} "x[%s] = " & (if x[k] < 0 then "?" else "%g"),
k, x[k];
\end{verbatim}
A sentença printf é similar a sentença display, no entanto, ela
permite formatar os dados a serem escritos.
Se um domínio do subíndice não é especificado, a sentença printf
é executada apenas uma vez. Especificar um domínio do subíndice gera
a execução da sentença printf para cada $n$-tupla no conjunto do domínio.
No último caso, o formato e a expressão podem incluir índices introduzidos
nas expressões indexantes correspondentes.
A cadeia de controle de formato é valor da expressão simbólica
{\it formato} especificada na sentença printf. Ela é composta de zero
ou mais diretivas, como segue: tanto caracteres ordinários (exceto {\tt\%}), que
são copiados sem modificação ao fluxo de saída, quanto especificações de conversão,
provocam a avaliação da expressão correspondente especificada na sentença
printf, do seu formato e da escrita do valor resultante no fluxo de saída.
As especificações de conversão que podem ser usadas na cadeia de controle
de formato são as seguintes: {\tt d}, {\tt i}, {\tt f}, {\tt F},
{\tt e}, {\tt E}, {\tt g}, {\tt G} e {\tt s}. Estas especificações
possuem a mesma sintaxe e semântica que na linguagem de programação C.
% \noindent
% \framebox[468pt][l]{
% \parbox[c][64pt]{468pt}{
% \hspace{6pt} {\tt printf} {\it domain} {\tt:} {\it format} {\tt,}
% {\it expression} {\tt,} \dots {\tt,} {\it expression} {\tt;}
%
% \medskip
%
% \hspace{6pt} {\tt printf} {\it domain} {\tt:} {\it format} {\tt,}
% {\it expression} {\tt,} \dots {\tt,} {\it expression} {\tt>}
% {\it filename} {\tt;}
%
% \medskip
%
% \hspace{6pt} {\tt printf} {\it domain} {\tt:} {\it format} {\tt,}
% {\it expression} {\tt,} \dots {\tt,} {\it expression} {\tt>>}
% {\it filename} {\tt;}
% }}
%
% \medskip
%
% \noindent
% {\it domain} is an optional indexing expression, which specifies
% a subscript domain of the printf statement;
%
% \noindent
% {\it format} is a symbolic expression whose value specifies a format
% control string. (The colon preceding the format expression may be
% omitted.)
%
% \noindent
% {\it expression}, \dots, {\it expression} are zero or more expressions
% whose values have to be formatted and printed. Each expression should
% be of numeric, symbolic, or logical type.
%
% \noindent
% {\it filename} is a symbolic expression whose value specifies a name
% of a text file, to which the output is redirected. The flag {\tt>}
% means creating a new empty file while the flag {\tt>>} means appending
% the output to an existing file. If no file name is specified, the
% output is written on the standard output (terminal).
%
% \para{Examples}
%
% \begin{verbatim}
% printf 'Hello, world!\n';
% printf: "x = %.3f; y = %.3f; z = %.3f\n", x, y, z > "result.txt";
% printf{i in I, j in J}: "flow from %s to %s is %d\n", i, j, x[i,j]
% >> result_file & ".txt";
% printf{i in I} 'total flow from %s is %g\n', i, sum{j in J} x[i,j];
% printf{k in K} "x[%s] = " & (if x[k] < 0 then "?" else "%g"),
% k, x[k];
% \end{verbatim}
%
% The printf statement is similar to the display statement, however, it
% allows formatting data to be written.
%
% If a subscript domain is not specified, the printf statement is
% executed only once. Specifying a subscript domain causes executing the
% printf statement for every $n$-tuple in the domain set. In the latter
% case the format and expression may include dummy indices introduced in
% corresponding indexing expression.
%
% The format control string is a value of the symbolic expression
% {\it format} specified in the printf statement. It is composed of zero
% or more directives as follows: ordinary characters (not {\tt\%}), which
% are copied unchanged to the output stream, and conversion
% specifications, each of which causes evaluating corresponding
% expression specified in the printf statement, formatting it, and
% writing its resultant value to the output stream.
%
% Conversion specifications that may be used in the format control string
% are the following:\linebreak {\tt d}, {\tt i}, {\tt f}, {\tt F},
% {\tt e}, {\tt E}, {\tt g}, {\tt G}, and {\tt s}. These specifications
% have the same syntax and semantics as in the C programming language.
\section{Sentença for}
\noindent
\framebox[468pt][l]{
\parbox[c][44pt]{468pt}{
\hspace{6pt} {\tt for} {\it domínio} {\tt:} {\it sentença} {\tt;}
\medskip
\hspace{6pt} {\tt for} {\it domínio} {\tt:} {\tt\{} {\it sentença}
\dots {\it sentença} {\tt\}} {\tt;}
}}
\medskip
\noindent
{\it domínio} é uma expressão indexante que especifica um
domínio do subíndice da sentença for. (Os dois pontos que seguem a
expressão indexante podem ser omitidos).
\noindent
{\it sentença} é uma sentença que deve ser executada sob o controle
da sentença for;
\noindent
{\it sentença}, \dots, {\it sentença} é uma sequência de sentenças
(cercada entre chaves) que deve ser executada sob o controle da
sentença for.
Apenas as sentenças seguintes podem ser usadas dentro da
sentença for: check, display, printf e outro for.
\para{Exemplos}
\begin{verbatim}
for {(i,j) in E: i != j}
{ printf "fluxo de %s para %s eh %g\n", i, j, x[i,j];
check x[i,j] >= 0;
}
for {i in 1..n}
{ for {j in 1..n} printf " %s", if x[i,j] then "Q" else ".";
printf("\n");
}
for {1..72} printf("*");
\end{verbatim}
A sentença for faz com que a sentença, ou uma sequência de sentenças
especificadas como parte da sentença for, seja executada para cada
$n$-tupla no conjunto do domínio. Assim, sentenças dentro da sentença for
podem incluir índices introduzidos na expressão indexante correspondente.
% \noindent
% \framebox[468pt][l]{
% \parbox[c][44pt]{468pt}{
% \hspace{6pt} {\tt for} {\it domain} {\tt:} {\it statement} {\tt;}
%
% \medskip
%
% \hspace{6pt} {\tt for} {\it domain} {\tt:} {\tt\{} {\it statement}
% \dots {\it statement} {\tt\}} {\tt;}
% }}
%
% \medskip
%
% \noindent
% {\it domain} is an indexing expression which specifies a subscript
% domain of the for statement. (The colon following the indexing
% expression may be omitted.)
%
% \noindent
% {\it statement} is a statement, which should be executed under control
% of the for statement;
%
% \noindent
% {\it statement}, \dots, {\it statement} is a sequence of statements
% (enclosed in curly braces), which should be executed under control of
% the for statement.
%
% Only the following statements can be used within the for statement:
% check, display, printf, and another for.
%
% \para{Examples}
%
% \begin{verbatim}
% for {(i,j) in E: i != j}
% { printf "flow from %s to %s is %g\n", i, j, x[i,j];
% check x[i,j] >= 0;
% }
% for {i in 1..n}
% { for {j in 1..n} printf " %s", if x[i,j] then "Q" else ".";
% printf("\n");
% }
% for {1..72} printf("*");
% \end{verbatim}
%
% The for statement causes a statement or a sequence of statements
% specified as part of the for statement to be executed for every
% $n$-tuple in the domain set. Thus, statements within the for statement
% may include dummy indices introduced in corresponding indexing
% expression.
\newpage
\section{Sentença table}
\noindent
\framebox[468pt][l]{
\parbox[c][80pt]{468pt}{
\hspace{6pt} {\tt table} {\it nome} {\it alias} {\tt IN} {\it controlador}
{\it arg} \dots {\it arg} {\tt:}
\hspace{6pt} {\tt\ \ \ \ \ } {\it conjunto} {\tt<-} {\tt[} {\it cmp} {\tt,}
\dots {\tt,} {\it cmp} {\tt]} {\tt,} {\it par} {\tt\textasciitilde}
{\it cmp} {\tt,} \dots {\tt,} {\it par} {\tt\textasciitilde} {\it cmp}
{\tt;}
\medskip
\hspace{6pt} {\tt table} {\it nome} {\it alias} {\it domínio} {\tt OUT}
{\it controlador} {\it arg} \dots {\it arg} {\tt:}
\hspace{6pt} {\tt\ \ \ \ \ } {\it expr} {\tt\textasciitilde} {\it cmp}
{\tt,} \dots {\tt,} {\it expr} {\tt\textasciitilde} {\it cmp} {\tt;}
}}
\medskip
\noindent
{\it nome} é um nome simbólico da tabela;
\noindent
{\it alias} é um literal de cadeia opcional que especifica um pseudônimo
da tabela;
\noindent
{\it domínio} é uma expressão indexante que especifica o domínio do
subíndice da tabela (de saída);
\noindent
{\tt IN} significa ler dados de uma tabela de entrada;
\noindent
{\tt OUT} significa escrever dados em uma tabela de saída;
\noindent
{\it controlador} é uma expressão simbólica que especifica o controlador
usado para acessar a tabela (para mais detalhes, ver Apêndice \ref{drivers},
página \pageref{drivers});
\noindent
{\it arg} é uma expressão simbólica opcional, que é um argumento
passado ao controlador da tabela. Esta expressão simbólica não deveria
incluir índices especificados no domínio;
\noindent
{\it conjunto} é o nome de um conjunto simples opcional chamado
{\it conjunto de controle}. Pode ser omitido junto com o delimitador {\tt<-};
\noindent
{\it cmp} é um nome de campo. Entre colchetes, pelo menos um campo deve ser
especificado. O nome do campo, que segue o nome do parâmetro ou de uma
expressão, é opcional e pode ser omitido juntamente com o
delimitador~{\tt\textasciitilde}. Neste caso o nome do objeto de modelo
correspondente é usado como nome de campo;
\noindent
{\it par} é um nome simbólico de um parâmetro do modelo;
\noindent
{\it expr} é uma expressão numérica ou simbólica.
\para{Exemplos}
\begin{verbatim}
table dados IN "CSV" "dados.csv": S <- [DE,PARA], d~DISTANCIA,
c~CUSTO;
table resultado{(d,p) in S} OUT "CSV" "resultado.csv": d~DE, p~PARA,
x[d,p]~FLUXO;
\end{verbatim}
A sentença table permite a leitura de dados de uma tabela para objetos
de modelo como conjuntos e parâmetros (não-escalares) assim como escrever
dados do modelo para uma tabela.
% \noindent
% \framebox[468pt][l]{
% \parbox[c][80pt]{468pt}{
% \hspace{6pt} {\tt table} {\it name} {\it alias} {\tt IN} {\it driver}
% {\it arg} \dots {\it arg} {\tt:}
%
% \hspace{6pt} {\tt\ \ \ \ \ } {\it set} {\tt<-} {\tt[} {\it fld} {\tt,}
% \dots {\tt,} {\it fld} {\tt]} {\tt,} {\it par} {\tt\textasciitilde}
% {\it fld} {\tt,} \dots {\tt,} {\it par} {\tt\textasciitilde} {\it fld}
% {\tt;}
%
% \medskip
%
% \hspace{6pt} {\tt table} {\it name} {\it alias} {\it domain} {\tt OUT}
% {\it driver} {\it arg} \dots {\it arg} {\tt:}
%
% \hspace{6pt} {\tt\ \ \ \ \ } {\it expr} {\tt\textasciitilde} {\it fld}
% {\tt,} \dots {\tt,} {\it expr} {\tt\textasciitilde} {\it fld} {\tt;}
% }}
%
% \medskip
%
% \noindent
% {\it name} is a symbolic name of the table;
%
% \noindent
% {\it alias} is an optional string literal, which specifies an alias of
% the table;
%
% \noindent
% {\it domain} is an indexing expression, which specifies a subscript
% domain of the (output) table;
%
% \noindent
% {\tt IN} means reading data from the input table;
%
% \noindent
% {\tt OUT} means writing data to the output table;
%
% \noindent
% {\it driver} is a symbolic expression, which specifies the driver used
% to access the table (for details see Appendix \ref{drivers}, page
% \pageref{drivers});
%
% \noindent
% {\it arg} is an optional symbolic expression, which is an argument
% pass\-ed to the table driver. This symbolic expression should not
% include dummy indices specified in the domain;
%
% \noindent
% {\it set} is the name of an optional simple set called {\it control
% set}. It can be omitted along with the delimiter {\tt<-};
%
% \noindent
% {\it fld} is a field name. Within square brackets at least one field
% should be specified. The field name following a parameter name or
% expression is optional and can be omitted along with the
% delimiter~{\tt\textasciitilde}, in which case the name of corresponding
% model object is used as the field name;
%
% \noindent
% {\it par} is a symbolic name of a model parameter;
%
% \noindent
% {\it expr} is a numeric or symbolic expression.
%
% \para{Examples}
%
% \begin{verbatim}
% table data IN "CSV" "data.csv": S <- [FROM,TO], d~DISTANCE,
% c~COST;
% table result{(f,t) in S} OUT "CSV" "result.csv": f~FROM, t~TO,
% x[f,t]~FLOW;
% \end{verbatim}
%
% The table statement allows reading data from a table into model
% objects such as sets and (non-scalar) parameters as well as writing
% data from the model to a table.
\newpage
\subsection{Estrutura de tabelas}
Uma {\it tabela de dados} é um conjunto (desordenado) de {\it registros}, onde cada
registro consiste do mesmo número de {\it campos} e cada campo possui um único
nome simbólico denominado o {\it nome do campo}. Por exemplo:
\bigskip
\begin{tabular}{@{\hspace*{42mm}}c@{\hspace*{11mm}}c@{\hspace*{10mm}}c
@{\hspace*{9mm}}c}
Primeiro&Segundo&&Último\\
campo&campo&.\ \ .\ \ .&campo\\
$\downarrow$&$\downarrow$&&$\downarrow$\\
\end{tabular}
\begin{tabular}{ll@{}}
Cabeçalho da tabela&$\rightarrow$\\
Primeiro registro&$\rightarrow$\\
Segundo registro&$\rightarrow$\\
\\
\hfil .\ \ .\ \ .\\
\\
Último registro&$\rightarrow$\\
\end{tabular}
\begin{tabular}{|l|l|c|c|}
\hline
{\tt DE}&{\tt PARA}&{\tt DISTANCIA}&{\tt CUSTO}\\
\hline
{\tt Seattle} &{\tt New-York}&{\tt 2.5}&{\tt 0.12}\\
{\tt Seattle} &{\tt Chicago} &{\tt 1.7}&{\tt 0.08}\\
{\tt Seattle} &{\tt Topeka} &{\tt 1.8}&{\tt 0.09}\\
{\tt San-Diego}&{\tt New-York}&{\tt 2.5}&{\tt 0.15}\\
{\tt San-Diego}&{\tt Chicago} &{\tt 1.8}&{\tt 0.10}\\
{\tt San-Diego}&{\tt Topeka} &{\tt 1.4}&{\tt 0.07}\\
\hline
\end{tabular}
% A {\it data table} is an (unordered) set of {\it records}, where each
% record consists of the same number of {\it fields}, and each field is
% provided with a unique symbolic name called the {\it field name}. For
% example:
%
% \bigskip
%
% \begin{tabular}{@{\hspace*{42mm}}c@{\hspace*{11mm}}c@{\hspace*{10mm}}c
% @{\hspace*{9mm}}c}
% First&Second&&Last\\
% field&field&.\ \ .\ \ .&field\\
% $\downarrow$&$\downarrow$&&$\downarrow$\\
% \end{tabular}
%
% \begin{tabular}{ll@{}}
% Table header&$\rightarrow$\\
% First record&$\rightarrow$\\
% Second record&$\rightarrow$\\
% \\
% \hfil .\ \ .\ \ .\\
% \\
% Last record&$\rightarrow$\\
% \end{tabular}
% \begin{tabular}{|l|l|c|c|}
% \hline
% {\tt FROM}&{\tt TO}&{\tt DISTANCE}&{\tt COST}\\
% \hline
% {\tt Seattle} &{\tt New-York}&{\tt 2.5}&{\tt 0.12}\\
% {\tt Seattle} &{\tt Chicago} &{\tt 1.7}&{\tt 0.08}\\
% {\tt Seattle} &{\tt Topeka} &{\tt 1.8}&{\tt 0.09}\\
% {\tt San-Diego}&{\tt New-York}&{\tt 2.5}&{\tt 0.15}\\
% {\tt San-Diego}&{\tt Chicago} &{\tt 1.8}&{\tt 0.10}\\
% {\tt San-Diego}&{\tt Topeka} &{\tt 1.4}&{\tt 0.07}\\
% \hline
% \end{tabular}
\subsection{Lendo dados de uma tabela de entrada}
A sentença tabela de entrada faz a leitura de dados
da tabela especificada, registro por registro.
Uma vez que o registro subsequente foi lido, valores numéricos ou simbólicos
dos campos, cujos nomes são cercados entre colchetes na sentença table,
são reunidos em um $n$-tuplo. Se o conjunto de controle é especificado
na sentença table, este $n$-tuplo é adicionado a ele. Além disso, um valor
numérico ou simbólico de cada campo associado com um parâmetro do modelo
é atribuído ao membro do parâmetro identificado por subíndices, que são
componentes da $n$-tupla que acabou de ser lida.
Por exemplo, a seguinte sentença de tabela de entrada:
\noindent\hfil
\verb|table dados IN "...": S <- [DE,PARA], d~DISTANCIA, c~CUSTO;|
\noindent
faz a leitura de valores de quatro campos chamados {\tt DE}, {\tt PARA},
{\tt DISTANCIA} e {\tt CUSTO} de cada registro da tabela especificada.
Os valores dos campos {\tt DE} e {\tt PARA} dão um par $(f,t)$, que é
adicionado ao conjunto de controle {\tt S}. O valor do campo {\tt DISTANCIA} é
atribuído ao membro do parâmetro ${\tt d}[f,t]$ enquanto que o valor do campo
{\tt CUSTO} é atribuído ao membro do parâmetro ${\tt c}[f,t]$.
Note que a tabela de entrada pode conter campos adicionais cujos nomes
não sejam especificados na sentença tabela, neste caso, os valores destes
campos serão ignorados na leitura da tabela.
% The input table statement causes reading data from the specified table
% record by record.
%
% Once a next record has been read, numeric or symbolic values of fields,
% whose names are enclosed in square brackets in the table statement, are
% gathered into $n$-tuple, and if the control set is specified in the
% table statement, this $n$-tuple is added to it. Besides, a numeric or
% symbolic value of each field associated with a model parameter is
% assigned to the parameter member identified by subscripts, which are
% components of the $n$-tuple just read.
%
% For example, the following input table statement:
%
% \noindent\hfil
% \verb|table data IN "...": S <- [FROM,TO], d~DISTANCE, c~COST;|
%
% \noindent
% causes reading values of four fields named {\tt FROM}, {\tt TO},
% {\tt DISTANCE}, and {\tt COST} from each record of the specified table.
% Values of fields {\tt FROM} and {\tt TO} give a pair $(f,t)$, which is
% added to the control set {\tt S}. The value of field {\tt DISTANCE} is
% assigned to parameter member ${\tt d}[f,t]$, and the value of field
% {\tt COST} is assigned to parameter member ${\tt c}[f,t]$.
%
% Note that the input table may contain extra fields whose names are not
% specified in the table statement, in which case values of these fields
% on reading the table are ignored.
\subsection{Escrevendo dados em uma tabela de saída}
A sentença tabela de saída gera a escrita de dados na tabela especificada.
Note que alguns controladores (chamados CSV e xBASE) destroem a tabela de saída
antes de escrever os dados, i.e., deletam todos os registros existentes.
Cada $n$-tupla no domínio do conjunto especificado gera um registro escrito na
tabela de saída. Os valores dos campos são valores numéricos ou simbólicos
das expressões correspondentes especificadas na sentença table. Estas
expressões são avaliadas para cada $n$-tupla no conjunto do domínio,
portanto, podem incluir índices introduzidos na expressão indexante correspondente.
Por exemplo, a seguinte sentença da tabela de saída:
\noindent\hfil
\verb|table resultado{(f,t) in S} OUT "...": f~DE, t~PARA, x[f,t]~FLUXO;|
\noindent
gera a escrita de registros; um registro para cada par $(f,t)$ no conjunto
{\tt S} para a tabela de saída, onde cada registro consiste de três campos
chamados {\tt DE}, {\tt PARA} e {\tt FLUXO}. Os valores escritos nos campos
{\tt DE} e {\tt PARA} são os valores correntes dos índices {\tt f} e {\tt t}.
O valor escrito no campo {\tt FLUXO} é um valor do membro ${\tt x}[f,t]$
do correspondente parâmetro ou variável indexada.
% The output table statement causes writing data to the specified table.
% Note that some drivers (namely, CSV and xBASE) destroy the output table
% before writing data, i.e. delete all its existing records.
%
% Each $n$-tuple in the specified domain set generates one record written
% to the output table. Values of fields are numeric or symbolic values of
% corresponding expressions specified in the table statement. These
% expressions are evaluated for each $n$-tuple in the domain set and,
% thus, may include dummy indices introduced in the corresponding indexing
% expression.
%
% For example, the following output table statement:
%
% \noindent\hfil
% \verb|table result{(f,t) in S} OUT "...": f~FROM, t~TO, x[f,t]~FLOW;|
%
% \noindent
% causes writing records, by one record for each pair $(f,t)$ in set
% {\tt S}, to the output table, where each record consists of three
% fields named {\tt FROM}, {\tt TO}, and {\tt FLOW}. The values written
% to fields {\tt FROM} and {\tt TO} are current values of dummy indices
% {\tt f} and {\tt t}, and the value written to field {\tt FLOW} is
% a value of member ${\tt x}[f,t]$ of corresponding subscripted parameter
% or variable.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\chapter{Dados do modelo}
Os {\it dados do modelo} includem conjuntos elementares, que são ``valores'' dos
conjuntos do modelo, e valores numéricos e simbólicos dos parâmetros do modelo.
Em MathProg existem duas formas diferentes de fornecer valores aos conjuntos
e parâmetros do modelo. Uma forma é simplesmente prover os dados necessários
usando o atributo de atribuição. No entanto, em muitos casos é mais prático separar
o modelo próprio dos dados particulares necessários para o modelo. Para o último
caso, em MathProg há uma outra forma, em que a descrição do modelo é dividida
em duas partes: a seção de modelo e a seção de dados.
A {\it seção de modelo} é a principal parte da descrição do modelo. Ela contém
todas as declarações de todos objetos do modelo, sendo comum a todos problemas
baseados naquele modelo.
A {\it seção de dados} é uma parte opcional da descrição do modelo que contém
dados específicos para um problema particular.
Em MathProg seções de modelo e de dados podem ser localizadas tanto em um arquivo
de texto ou em dois arquivos de texto separados.
1. Se ambas seções de modelo e de dados estão localizados em um arquivo,
o arquivo é composto como segue:
\bigskip
\noindent\hfil
\framebox{\begin{tabular}{l}
{\it sentença}{\tt;}\\
{\it sentença}{\tt;}\\
\hfil.\ \ .\ \ .\\
{\it sentença}{\tt;}\\
{\tt data;}\\
{\it bloco de dados}{\tt;}\\
{\it bloco de dados}{\tt;}\\
\hfil.\ \ .\ \ .\\
{\it bloco de dados}{\tt;}\\
{\tt end;}
\end{tabular}}
% {\it Model data} include elemental sets, which are ``values'' of model
% sets, and numeric and symbolic values of model parameters.
%
% In MathProg there are two different ways to saturate model sets and
% parameters with data. One way is simply providing necessary data using
% the assign attribute. However, in many cases it is more practical to
% separate the model itself and particular data needed for the model. For
% the latter reason in MathProg there is another way, when the model
% description is divided into two parts: model section and data section.
%
% A {\it model section} is a main part of the model description that
% contains declarations of all model objects and is common for all
% problems based on that model.
%
% A {\it data section} is an optional part of the model description that
% contains model data specific for a particular problem.
%
% In MathProg model and data sections can be placed either in one text
% file or in two separate text files.
%
% 1. If both model and data sections are placed in one file, the file is
% composed as follows:
%
% \bigskip
%
% \noindent\hfil
% \framebox{\begin{tabular}{l}
% {\it statement}{\tt;}\\
% {\it statement}{\tt;}\\
% \hfil.\ \ .\ \ .\\
% {\it statement}{\tt;}\\
% {\tt data;}\\
% {\it data block}{\tt;}\\
% {\it data block}{\tt;}\\
% \hfil.\ \ .\ \ .\\
% {\it data block}{\tt;}\\
% {\tt end;}
% \end{tabular}}
% 2. Se a seção de modelo e dados são posicionados em dois arquivos separados, os
% arquivos são compostos como segue:
\newpage
2. Se a seção de modelo e dados são posicionados em dois arquivos separados, os
arquivos são compostos como segue:
\bigskip
\noindent\hfil
\begin{tabular}{@{}c@{}}
\framebox{\begin{tabular}{l}
{\it sentença}{\tt;}\\
{\it sentença}{\tt;}\\
\hfil.\ \ .\ \ .\\
{\it sentença}{\tt;}\\
{\tt end;}\\
\end{tabular}}\\
\\\\Arquivo de modelo\\
\end{tabular}
\hspace{32pt}
\begin{tabular}{@{}c@{}}
\framebox{\begin{tabular}{l}
{\tt data;}\\
{\it bloco de dados}{\tt;}\\
{\it bloco de dados}{\tt;}\\
\hfil.\ \ .\ \ .\\
{\it bloco de dados}{\tt;}\\
{\tt end;}\\
\end{tabular}}\\
\\Arquivo de dados\\
\end{tabular}
\bigskip
Nota: Se a seção de dados é posicionada em um arquivo separado, a palavra-chave
{\tt data} é opcional e pode ser omitida juntamente como o ponto e vírgula que a segue.
% \bigskip
%
% \noindent\hfil
% \begin{tabular}{@{}c@{}}
% \framebox{\begin{tabular}{l}
% {\it statement}{\tt;}\\
% {\it statement}{\tt;}\\
% \hfil.\ \ .\ \ .\\
% {\it statement}{\tt;}\\
% {\tt end;}\\
% \end{tabular}}\\
% \\\\Model file\\
% \end{tabular}
% \hspace{32pt}
% \begin{tabular}{@{}c@{}}
% \framebox{\begin{tabular}{l}
% {\tt data;}\\
% {\it data block}{\tt;}\\
% {\it data block}{\tt;}\\
% \hfil.\ \ .\ \ .\\
% {\it data block}{\tt;}\\
% {\tt end;}\\
% \end{tabular}}\\
% \\Data file\\
% \end{tabular}
%
% \bigskip
%
% Note: If the data section is placed in a separate file, the keyword
% {\tt data} is optional and may be omitted along with the semicolon that
% follows it.
\section{Programando a seção de dados}
A {\it seção de dados} é uma sequência de blocos de dados em vários formatos
e são discutidos nas seções seguintes. A ordem na qual os blocos de dados
seguem na seção de dados pode ser arbitrária, portanto, não precisa ser
necessariamente a mesma ordem que seguem os elementos correspondentes
da seção de modelo.
As regras para programar a seção de dados são comumente as mesmas que as regras
de \linebreak programar a descrição do modelo (ver Seção \ref{coding}, página
\pageref{coding}), i.e., blocos de dados são compostos com unidades léxicas
básicas, como nomes simbólicos, literais numéricos e de cadeia,
palavras-chave, \linebreak delimitadores e comentários. No entanto, por conveniência
e para melhorar legibilidade, há um desvio da regra comum: se um literal
de cadeia consiste unicamente de caracteres alfanuméricos (incluindo
o caractere sublinhado), os sinais {\tt+} e {\tt-} e/ou o ponto decimal,
ele pode ser programado sem aspas limitadoras (simples ou duplas).
Todo material numérico e simbólico provido na seção de dados é programado
na forma de números e símbolos, i.e., diferentemente da seção de modelo,
não são permitidas expressões na seção de dados. Apesar disso, os sinais
{\tt+} e {\tt-} podem preceder literais numéricos para permitir a programação
de quantidades numéricas com sinais. Neste caso não deve haver caractere de
espaço em branco entre o sinal e o literal numérico seguinte (se houver
pelo menos uma espaço em branco, o sinal e o literal numérico seguinte são
reconhecidos como duas unidades léxicas diferentes).
% The {\it data section} is a sequence of data blocks in various formats,
% which are discussed in following sections. The order, in which data
% blocks follow in the data section, may be arbitrary, not necessarily
% the same, in which corresponding model objects follow in the model
% section.
%
% The rules of coding the data section are commonly the same as the rules
% of coding the model description (see Section \ref{coding}, page
% \pageref{coding}), i.e. data blocks are composed from basic lexical
% units such as symbolic names, numeric and string literals, keywords,
% delimiters, and comments. However, for the sake of convenience and for
% improving readability there is one deviation from the common rule: if
% a string literal consists of only alphanumeric characters (including
% the underscore character), the signs {\tt+} and {\tt-}, and/or the
% decimal point, it may be coded without bordering by (single or double)
% quotes.
%
% All numeric and symbolic material provided in the data section is coded
% in the form of numbers and symbols, i.e. unlike the model section
% no expressions are allowed in the data section. Nevertheless, the signs
% {\tt+} and {\tt-} can precede numeric literals to allow coding signed
% numeric quantities, in which case there should be no white-space
% characters between the sign and following numeric literal (if there is
% at least one white-space, the sign and following numeric literal are
% recognized as two different lexical units).
\newpage
\section{Bloco de dados set}
\noindent
\framebox[468pt][l]{
\parbox[c][44pt]{468pt}{
\hspace{6pt} {\tt set} {\it nome} {\tt,} {\it registro} {\tt,} \dots
{\tt,} {\it registro} {\tt;}
\medskip
\hspace{6pt} {\tt set} {\it nome} {\tt[} {\it símbolo} {\tt,} \dots
{\tt,} {\it símbolo} {\tt]} {\tt,} {\it registro} {\tt,} \dots {\tt,}
{\it registro} {\tt;}
}}
\medskip
\noindent
{\it nome} é um nome simbólico do conjunto;
\noindent
{\it símbolo}, \dots, {\it símbolo} são subíndices que especificam
um membro particular do conjunto \linebreak(se o conjunto é uma matriz, i.e.,
um conjunto de conjuntos);
\noindent
{\it registro}, \dots, {\it registro} são registros.
\noindent
As vírgulas que precedem os registros podem ser omitidas.
\para{Registros}
\vspace*{-8pt}
\begin{description}
\item[{\tt :=}]\hspace*{0pt}\\
é um elemento de atribuição de registro não-significativo que pode ser usado
livremente para melhorar a legibilidade;
\item[{\tt(} {\it fatia} {\tt)}]\hspace*{0pt}\\
especifica uma fatia;
\item[{\it dados-simples}]\hspace*{0pt}\\
especifica os dados do conjunto em formato simples;
\item[{\tt:} {\it dados matriciais}]\hspace*{0pt}\\
especifica os dados do conjunto em formato de matriz;
\item[{\tt(tr)} {\tt:} {\it dados matriciais}]\hspace*{0pt}\\
especifica os dados do conjunto em formato de matriz transposta.
(Neste caso, os dois pontos que seguem a palavra-chave {\tt(tr)} podem ser omitidos).
\end{description}
\vspace*{-8pt}
\para{Exemplos}
\begin{verbatim}
set mes := Jan Fev Mar Abr Mai Jun;
set mes "Jan", "Fev", "Mar", "Abr", "Mai", "Jun";
set A[3,Mar] := (1,2) (2,3) (4,2) (3,1) (2,2) (4,4) (3,4);
set A[3,'Mar'] := 1 2 2 3 4 2 3 1 2 2 4 4 3 4;
set A[3,'Mar'] : 1 2 3 4 :=
1 - + - -
2 - + + -
3 + - - +
4 - + - + ;
set B := (1,2,3) (1,3,2) (2,3,1) (2,1,3) (1,2,2) (1,1,1) (2,1,1);
set B := (*,*,*) 1 2 3, 1 3 2, 2 3 1, 2 1 3, 1 2 2, 1 1 1, 2 1 1;
set B := (1,*,2) 3 2 (2,*,1) 3 1 (1,2,3) (2,1,3) (1,1,1);
set B := (1,*,*) : 1 2 3 :=
1 + - -
2 - + +
3 - + -
(2,*,*) : 1 2 3 :=
1 + - +
2 - - -
3 + - - ;
\end{verbatim}
\noindent(Nestes exemplos {\tt mes} é um conjunto simples de singletos,
{\tt A} é uma matriz 2-dimensional de duplas e {\tt B} é um conjunto
simples de triplas. Os blocos de dados para o mesmo conjunto são equivalentes
no sentido que especificam os mesmos dados em formatos distintos.)
O {\it bloco de dados do conjunto} é usado para especificar um conjunto elementar
completo que é atribuído a um conjunto (se é um conjunto simples) ou a um de
seus membros (se o conjunto é uma matriz de conjuntos).\footnote{Há uma outra forma
de especificar dados para um conjunto simples com dados para os parâmetros.
Esta questão é discutida na próxima seção.}
Blocos de dados podem ser especificados somente para conjuntos não-calculáveis,
i.e., para \linebreak conjuntos que possuem o atributo de atribuição ({\tt:=})
na sentença set correspondente.
Se o conjunto é um conjunto simples, somente seus nomes simbólicos devem ser
especificados no cabeçalho do bloco de dados. Caso contrário, se o conjunto
é uma matriz $n$-dimensional, seus nomes simbólicos devem ser fornecidos com
uma lista completa de subíndices separados por vírgulas e cercados em colchetes
para especificar um membro particular da matriz de conjuntos. O número de
subíndices deve ser igual ao da dimensão da matriz de conjuntos, onde
cada subíndice deve ser um número ou um símbolo.
Um conjunto elementar definido no bloco de dados é programado como uma sequência
de \linebreak registros descritos abaixo.\footnote{{\it Registro} é simplesmente
um termo técnico. Não significa que os mesmos possuem qualquer formato
especial.}
% \noindent
% \framebox[468pt][l]{
% \parbox[c][44pt]{468pt}{
% \hspace{6pt} {\tt set} {\it name} {\tt,} {\it record} {\tt,} \dots
% {\tt,} {\it record} {\tt;}
%
% \medskip
%
% \hspace{6pt} {\tt set} {\it name} {\tt[} {\it symbol} {\tt,} \dots
% {\tt,} {\it symbol} {\tt]} {\tt,} {\it record} {\tt,} \dots {\tt,}
% {\it record} {\tt;}
% }}
%
% \medskip
%
% \noindent
% {\it name} is a symbolic name of the set;
%
% \noindent
% {\it symbol}, \dots, {\it symbol} are subscripts, which specify
% a particular member of the set (if the set is an array, i.e. a set of
% sets);
%
% \noindent
% {\it record}, \dots, {\it record} are data records.
%
% \noindent
% Commae preceding data records may be omitted.
%
% \para{Data records}
%
% \vspace*{-8pt}
%
% \begin{description}
% \item[{\tt :=}]\hspace*{0pt}\\
% is a non-significant data record, which may be used freely to improve
% readability;
% \item[{\tt(} {\it slice} {\tt)}]\hspace*{0pt}\\
% specifies a slice;
% \item[{\it simple-data}]\hspace*{0pt}\\
% specifies set data in the simple format;
% \item[{\tt:} {\it matrix-data}]\hspace*{0pt}\\
% specifies set data in the matrix format;
% \item[{\tt(tr)} {\tt:} {\it matrix-data}]\hspace*{0pt}\\
% specifies set data in the transposed matrix format. (In this case the
% colon following the keyword {\tt(tr)} may be omitted.)
% \end{description}
%
% \vspace*{-8pt}
%
% \para{Examples}
%
% \begin{verbatim}
% set month := Jan Feb Mar Apr May Jun;
% set month "Jan", "Feb", "Mar", "Apr", "May", "Jun";
% set A[3,Mar] := (1,2) (2,3) (4,2) (3,1) (2,2) (4,4) (3,4);
% set A[3,'Mar'] := 1 2 2 3 4 2 3 1 2 2 4 4 3 4;
% set A[3,'Mar'] : 1 2 3 4 :=
% 1 - + - -
% 2 - + + -
% 3 + - - +
% 4 - + - + ;
% set B := (1,2,3) (1,3,2) (2,3,1) (2,1,3) (1,2,2) (1,1,1) (2,1,1);
% set B := (*,*,*) 1 2 3, 1 3 2, 2 3 1, 2 1 3, 1 2 2, 1 1 1, 2 1 1;
% set B := (1,*,2) 3 2 (2,*,1) 3 1 (1,2,3) (2,1,3) (1,1,1);
% set B := (1,*,*) : 1 2 3 :=
% 1 + - -
% 2 - + +
% 3 - + -
% (2,*,*) : 1 2 3 :=
% 1 + - +
% 2 - - -
% 3 + - - ;
% \end{verbatim}
%
% \noindent(In these examples {\tt month} is a simple set of singlets,
% {\tt A} is a 2-dimensional array of doublets, and {\tt B} is a simple
% set of triplets. Data blocks for the same set are equivalent in the
% sense that they specify the same data in different formats.)
%
% The {\it set data block} is used to specify a complete elemental set,
% which is assigned to a set (if it is a simple set) or one of its
% members (if the set is an array of sets).\footnote{There is another way
% to specify data for a simple set along with data for parameters. This
% feature is discussed in the next section.}
%
% Data blocks can be specified only for non-computable sets, i.e. for
% sets, which have no assign attribute ({\tt:=}) in the corresponding set
% statements.
%
% If the set is a simple set, only its symbolic name should be specified
% in the header of the data block. Otherwise, if the set is a
% $n$-dimensional array, its symbolic name should be provided with a
% complete list of subscripts separated by commae and enclosed in square
% brackets to specify a particular member of the set array. The number of
% subscripts should be the same as the dimension of the set array, where
% each subscript should be a number or symbol.
%
% An elemental set defined in the set data block is coded as a sequence
% of data records described below.\footnote{{\it Data record} is simply a
% technical term. It does not mean that data records have any special
% formatting.}
\subsection{Registro de atribuição de dados}
O {\it registro de atribuição de dados} ({\tt:=}) é um elemento não-significante.
Ele pode ser usado para melhorar a legibilidade de blocos de dados.
% The {\it assign data record} ({\tt:=}) is a non-signficant element.
% It may be used for improving readability of data blocks.
\subsection{Registro em fatia de dados}
O {\it registro em fatia de dados} é um registro de controle que especifica
uma {\it fatia} do conjunto elementar definido no bloco de dados. Ele possui
a seguinte forma sintática:
$$\mbox{{\tt(} $s_1$ {\tt,} $s_2$ {\tt,} \dots {\tt,} $s_n$ {\tt)}}$$
onde $s_1$, $s_2$, \dots, $s_n$ são componentes da fatia.
Cada componente da fatia pode ser um número, símbolo ou asterisco
({\tt*}). O número de \linebreak componentes na fatia deve ser o mesmo da
dimensão $n$-tuplas do conjunto elementar a ser definido. Por exemplo,
se o conjunto elementar contém 4-tuplas (quádruplas), a fatia deve ter
quatro \linebreak componentes. O número de asteriscos na fatia denomina a
{\it dimensão da fatia}.
O efeito de usar fatias é o seguinte: se uma fatia $m$-dimensional
(i.e., uma fatia contendo $m$ asteriscos) é especificada no bloco de dados,
todos registros subsequentes devem especificar tuplas de dimensão~$m$.
Sempre que uma $m$-tupla é encontrada, cada asterisco da fatia é substituído
pelos componentes correspondentes da $m$-tupla, o que resulta na
$n$-tupla, que é incluída no conjunto \linebreak elementar a ser definido.
Por exemplo, se a fatia $(a,*,1,2,*)$ está vigente e a dupla
$(3,b)$ é encontrada no registro subsequente, a 5-tupla resultante a ser incluída
no conjunto elementar é $(a,3,1,2,b)$.
Se a fatia não possui asteriscos, ela própria define uma $n$-tupla completa
que é incluída no conjunto elementar.
Uma vez especificada uma fatia, a mesma está vigente até que apareça uma nova
fatia ou até que se encontre o fim do bloco de dados. Note que se uma fatia
não é especificada no bloco de dados, assume-se uma cujos componentes são
asteriscos em todas as posições.
% The {\it slice data record} is a control record, which specifies a
% {\it slice} of the elemental set defined in the data block. It has the
% following syntactic form:
% $$\mbox{{\tt(} $s_1$ {\tt,} $s_2$ {\tt,} \dots {\tt,} $s_n$ {\tt)}}$$
% where $s_1$, $s_2$, \dots, $s_n$ are components of the slice.
%
% Each component of the slice can be a number or symbol or the asterisk
% ({\tt*}). The number of components in the slice should be the same as
% the dimension of $n$-tuples in the elemental set to be defined. For
% instance, if the elemental set contains 4-tuples (quadruplets), the
% slice should have four components. The number of asterisks in the slice
% is called the {\it slice dimension}.
%
% The effect of using slices is the following. If a $m$-dimensional slice
% (i.e. a slice having $m$ asterisks) is specified in the data block, all
% subsequent data records should specify tuples of the dimension~$m$.
% Whenever a $m$-tuple is encountered, each asterisk in the slice is
% replaced by corresponding components of the $m$-tuple that gives the
% resultant $n$-tuple, which is included in the elemental set to be
% defined. For example, if the slice $(a,*,1,2,*)$ is in effect, and
% 2-tuple $(3,b)$ is encountered in a subsequent data record, the
% resultant 5-tuple included in the elemental set is $(a,3,1,2,b)$.
%
% The slice having no asterisks itself defines a complete $n$-tuple,
% which is included in the elemental set.
%
% Being once specified the slice effects until either a new slice or the
% end of data block is encountered. Note that if no slice is specified in
% the data block, one, components of which are all asterisks, is assumed.
\subsection{Registro simples}
O {\it registro simples} define uma $n$-tupla em um formato simples
e possui a seguinte forma sintática:
$$\mbox{$t_1$ {\tt,} $t_2$ {\tt,} \dots {\tt,} $t_n$}$$
onde $t_1$, $t_2$, \dots, $t_n$ são componentes da $n$-tupla. Cada
componente pode ser um número ou um símbolo. As vírgulas entre os componentes
são opcionais e podem ser omitidas.
% The {\it simple data record} defines one $n$-tuple in a simple format
% and has the following syntactic form:
% $$\mbox{$t_1$ {\tt,} $t_2$ {\tt,} \dots {\tt,} $t_n$}$$
% where $t_1$, $t_2$, \dots, $t_n$ are components of the $n$-tuple. Each
% component can be a number or symbol. Commae between components are
% optional and may be omitted.
\subsection{Registro de matriz}
O {\it registro de matriz} define diversas 2-tuplas (duplas) em
um formato matricial e possui a seguinte forma sintática:
$$\begin{array}{cccccc}
\mbox{{\tt:}}&c_1&c_2&\dots&c_n&\mbox{{\tt:=}}\\
r_1&a_{11}&a_{12}&\dots&a_{1n}&\\
r_2&a_{21}&a_{22}&\dots&a_{2n}&\\
\multicolumn{5}{c}{.\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .}&\\
r_m&a_{m1}&a_{m2}&\dots&a_{mn}&\\
\end{array}$$
onde $r_1$, $r_2$, \dots, $r_m$ são números e/ou símbolos
que correspondem a linhas da matriz; $c_1$, $c_2$, \dots, $c_n$ são
números e/ou símbolos que correspondem a colunas da matriz, $a_{11}$,
$a_{12}$, \dots, $a_{mn}$ são elementos da matriz, que podem ser tanto
{\tt+} como {\tt-}. (Neste registro, o delimitador {\tt:} que precede a
lista de colunas e o delimitador {\tt:=} que segue após a lista de colunas,
não podem ser omitidos.)
Cada elemento $a_{ij}$ do bloco de dados matricial (onde $1\leq i\leq m$,
$1\leq j\leq n$) correspondem a 2-tuplas $(r_i,c_j)$. Se $a_{ij}$ é o
sinal mais ({\tt+}), a 2-tupla correspondente (ou uma $n$-tupla maior, se uma
fatia é usada) é incluída no conjunto elementar. Caso contrário, se $a_{ij}$ é o
sinal menos ({\tt-}), aquela 2-tupla não é incluída no conjunto elementar.
Uma vez que o registro de matriz define 2-tuplas, tanto o conjunto elementar
quanto a fatia vigente devem ser 2-dimensional.
\newpage
\subsection{Registro de matriz transposta}
O {\it registro de matriz transposta} possui a seguinte forma sintática:
$$\begin{array}{cccccc}
\mbox{{\tt(tr) :}}&c_1&c_2&\dots&c_n&\mbox{{\tt:=}}\\
r_1&a_{11}&a_{12}&\dots&a_{1n}&\\
r_2&a_{21}&a_{22}&\dots&a_{2n}&\\
\multicolumn{5}{c}{.\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .}&\\
r_m&a_{m1}&a_{m2}&\dots&a_{mn}&\\
\end{array}$$
(Neste caso, o delimitador {\tt:} que segue a palavra-chave {\tt(tr)} é
opcional e pode ser omitido.)
Este registro é completamente análogo ao registro de matriz (ver
anteriormente) com a única exceção de que neste caso, cada elemento $a_{ij}$ da
matriz passa a corresponder a 2-tupla $(c_j,r_i)$ ao invés de $(r_i,c_j)$.
Uma vez especificado, o indicador {\tt(tr)} tem alcance em todos registros
subsequentes até que se encontre outra fatia ou o fim do bloco de dados.
% The {\it transposed matrix data record} has the following syntactic
% form:
% $$\begin{array}{cccccc}
% \mbox{{\tt(tr) :}}&c_1&c_2&\dots&c_n&\mbox{{\tt:=}}\\
% r_1&a_{11}&a_{12}&\dots&a_{1n}&\\
% r_2&a_{21}&a_{22}&\dots&a_{2n}&\\
% \multicolumn{5}{c}{.\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .}&\\
% r_m&a_{m1}&a_{m2}&\dots&a_{mn}&\\
% \end{array}$$
% (In this case the delimiter {\tt:} following the keyword {\tt(tr)} is
% optional and may be omitted.)
%
% This data record is completely analogous to the matrix data record (see
% above) with only exception that in this case each element $a_{ij}$ of
% the matrix corresponds to 2-tuple $(c_j,r_i)$ rather than $(r_i,c_j)$.
%
% Being once specified the {\tt(tr)} indicator affects all subsequent
% data records until either a slice or the end of data block is
% encountered.
\section{Bloco de dados de parâmetro}
\noindent
\framebox[468pt][l]{
\parbox[c][88pt]{468pt}{
\hspace{6pt} {\tt param} {\it nome} {\tt,} {\it registro} {\tt,} \dots
{\tt,} {\it registro} {\tt;}
\medskip
\hspace{6pt} {\tt param} {\it nome} {\tt default} {\it valor} {\tt,}
{\it registro} {\tt,} \dots {\tt,} {\it registro} {\tt;}
\medskip
\hspace{6pt} {\tt param} {\tt:} {\it dados-tabulação} {\tt;}
\medskip
\hspace{6pt} {\tt param} {\tt default} {\it valor} {\tt:}
{\it dados-tabulação} {\tt;}
}}
\medskip
\noindent
{\it nome} é um nome simbólico do parâmetro;
\noindent
{\it valor} é um valor opcional padrão do parâmetro;
\noindent
{\it registro}, \dots, {\it registro} são registros;
\noindent
{\it dados-tabulação} especifica os dados do parâmetro em formato tabulação.
\noindent
As vírgulas que precedem os registros podem ser omitidas.
\para{Registros}
\vspace*{-8pt}
\begin{description}
\item[{\tt :=}]\hspace*{0pt}\\
é um elemento de atribuição de registro não-significativo que pode ser usado
livremente para melhorar a legibilidade;
\item[{\tt[} {\it fatia} {\tt]}]\hspace*{0pt}\\
especifica uma fatia;
\item[{\it dados-planos}]\hspace*{0pt}\\
especifica os dados do parâmetro em formato simples;
\item[{\tt:} {\it dados-tabulares}]\hspace*{0pt}\\
especifica dados do parâmetro em formato tabular;
\item[{\tt(tr)} {\tt:} {\it dados-tabulares}]\hspace*{0pt}\\
especifica dados do parâmetro no formato tabular transposto.
(Neste caso, os dois pontos que seguem a palavra-chave {\tt(tr)} podem ser omitidos).
\end{description}
\vspace*{-8pt}
\para{Exemplos}
\begin{verbatim}
param T := 4;
param mes := 1 Jan 2 Fev 3 Mar 4 Abr 5 Mai;
param mes := [1] 'Jan', [2] 'Fev', [3] 'Mar', [4] 'Abr', [5] 'Mai';
param estoque_inicial := ferro 7.32 niquel 35.8;
param estoque_inicial [*] ferro 7.32, niquel 35.8;
param custo [ferro] .025 [niquel] .03;
param valor := ferro -.1, niquel .02;
param : estoque_inicial custo valor :=
ferro 7.32 .025 -.1
niquel 35.8 .03 .02 ;
param : insumo : estoque_inicial custo valor :=
ferro 7.32 .025 -.1
niquel 35.8 .03 .02 ;
param demanda default 0 (tr)
: FRA DET LAN WIN STL FRE LAF :=
chapa 300 . 100 75 . 225 250
bobina 500 750 400 250 . 850 500
placa 100 . . 50 200 . 250 ;
param custo_transporte :=
[*,*,chapa]: FRA DET LAN WIN STL FRE LAF :=
GARY 30 10 8 10 11 71 6
CLEV 22 7 10 7 21 82 13
PITT 19 11 12 10 25 83 15
[*,*,bobina]: FRA DET LAN WIN STL FRE LAF :=
GARY 39 14 11 14 16 82 8
CLEV 27 9 12 9 26 95 17
PITT 24 14 17 13 28 99 20
[*,*,placa]: FRA DET LAN WIN STL FRE LAF :=
GARY 41 15 12 16 17 86 8
CLEV 29 9 13 9 28 99 18
PITT 26 14 17 13 31 104 20 ;
\end{verbatim}
O {\it bloco de dados do parâmetro} é usado para especificar dados
completos para um parâmetro (ou parâmetros, se os dados são especificados
no formato tabulação).
Os blocos de dados podem ser especificados apenas para parâmetros não-calculáveis, i.e.,
para parâmetros que não possuem o atributo de atribuição ({\tt:=}) nas
sentenças parameter correspondentes.
Os dados definidos no bloco de dados do parâmetro são programados como uma sequência
de registros descritos em seguida. Adicionalmente, o bloco de dados pode vir com
o atributo opcional {\tt default}, que especifica um valor numérico ou simbólico
padrão do parâmetro (ou parâmetros). Este valor padrão é atribuído ao parâmetro ou
a seus membros quando não se definem valores apropriados no bloco de dados do
parâmetro. O atributo {\tt default} não pode ser usado se ele já tiver sido
especificado na sentença parameter correspondente.
% \noindent
% \framebox[468pt][l]{
% \parbox[c][88pt]{468pt}{
% \hspace{6pt} {\tt param} {\it name} {\tt,} {\it record} {\tt,} \dots
% {\tt,} {\it record} {\tt;}
%
% \medskip
%
% \hspace{6pt} {\tt param} {\it name} {\tt default} {\it value} {\tt,}
% {\it record} {\tt,} \dots {\tt,} {\it record} {\tt;}
%
% \medskip
%
% \hspace{6pt} {\tt param} {\tt:} {\it tabbing-data} {\tt;}
%
% \medskip
%
% \hspace{6pt} {\tt param} {\tt default} {\it value} {\tt:}
% {\it tabbing-data} {\tt;}
% }}
%
% \medskip
%
% \noindent
% {\it name} is a symbolic name of the parameter;
%
% \noindent
% {\it value} is an optional default value of the parameter;
%
% \noindent
% {\it record}, \dots, {\it record} are data records;
%
% \noindent
% {\it tabbing-data} specifies parameter data in the tabbing format.
%
% \noindent
% Commae preceding data records may be omitted.
%
% \para{Data records}
%
% \vspace*{-8pt}
%
% \begin{description}
% \item[{\tt :=}]\hspace*{0pt}\\
% is a non-significant data record, which may be used freely to improve
% readability;
% \item[{\tt[} {\it slice} {\tt]}]\hspace*{0pt}\\
% specifies a slice;
% \item[{\it plain-data}]\hspace*{0pt}\\
% specifies parameter data in the plain format;
% \item[{\tt:} {\it tabular-data}]\hspace*{0pt}\\
% specifies parameter data in the tabular format;
% \item[{\tt(tr)} {\tt:} {\it tabular-data}]\hspace*{0pt}\\
% specifies set data in the transposed tabular format. (In this case the
% colon following the keyword {\tt(tr)} may be omitted.)
% \end{description}
%
% \vspace*{-8pt}
%
% \para{Examples}
%
% \begin{verbatim}
% param T := 4;
% param month := 1 Jan 2 Feb 3 Mar 4 Apr 5 May;
% param month := [1] 'Jan', [2] 'Feb', [3] 'Mar', [4] 'Apr', [5] 'May';
% param init_stock := iron 7.32 nickel 35.8;
% param init_stock [*] iron 7.32, nickel 35.8;
% param cost [iron] .025 [nickel] .03;
% param value := iron -.1, nickel .02;
% param : init_stock cost value :=
% iron 7.32 .025 -.1
% nickel 35.8 .03 .02 ;
% param : raw : init stock cost value :=
% iron 7.32 .025 -.1
% nickel 35.8 .03 .02 ;
% param demand default 0 (tr)
% : FRA DET LAN WIN STL FRE LAF :=
% bands 300 . 100 75 . 225 250
% coils 500 750 400 250 . 850 500
% plate 100 . . 50 200 . 250 ;
% param trans_cost :=
% [*,*,bands]: FRA DET LAN WIN STL FRE LAF :=
% GARY 30 10 8 10 11 71 6
% CLEV 22 7 10 7 21 82 13
% PITT 19 11 12 10 25 83 15
% [*,*,coils]: FRA DET LAN WIN STL FRE LAF :=
% GARY 39 14 11 14 16 82 8
% CLEV 27 9 12 9 26 95 17
% PITT 24 14 17 13 28 99 20
% [*,*,plate]: FRA DET LAN WIN STL FRE LAF :=
% GARY 41 15 12 16 17 86 8
% CLEV 29 9 13 9 28 99 18
% PITT 26 14 17 13 31 104 20 ;
% \end{verbatim}
%
% The {\it parameter data block} is used to specify complete data for a
% parameter (or parameters, if data are specified in the tabbing format).
%
% Data blocks can be specified only for non-computable parameters, i.e.
% for parameters, which have no assign attribute ({\tt:=}) in the
% corresponding parameter statements.
%
% Data defined in the parameter data block are coded as a sequence of
% data records described below. Additionally the data block can be
% provided with the optional {\tt default} attribute, which specifies a
% default numeric or symbolic value of the parameter (parameters). This
% default value is assigned to the parameter or its members when
% no appropriate value is defined in the parameter data block. The
% {\tt default} attribute cannot be used, if it is already specified in
% the corresponding parameter statement.
\subsection{Registro de atribuição}
O {\it registro de atribuição} ({\tt:=}) é um elemento não-significativo.
Ele pode ser usado para melhorar a legibilidade dos blocos de dados;
% The {\it assign data record} ({\tt:=}) is a non-signficant element.
% It may be used for improving readability of data blocks.
\subsection{Registro em fatia}
O {\it registro em fatia} é um registro de controle que especifica uma
{\it fatia} da matriz do parâmetro. Ele tem a seguinte forma sintática:
$$\mbox{{\tt[} $s_1$ {\tt,} $s_2$ {\tt,} \dots {\tt,} $s_n$ {\tt]}}$$
onde $s_1$, $s_2$, \dots, $s_n$ são componentes da fatia.
Cada componente da fatia pode ser um número, símbolo ou asterisco
({\tt*}). O número de componentes na fatia deve ser o mesmo da
dimensão $n$-tuplas do parâmetro. Por exemplo,
se o parâmetro é uma matriz 4-dimensional, a fatia deve ter
quatro componentes. O número de \linebreak asteriscos na fatia denomina a
{\it dimensão da fatia}.
O efeito de usar fatias é o seguinte: se uma fatia $m$-dimensional
(i.e., uma fatia contendo $m$ asteriscos) é especificada no bloco de dados,
todos registros subsequentes devem especificar os subíndices do membros do
parâmetro, como se o parâmetro fosse $m$-dimensional, não $n$-dimensional.
Sempre que $m$ subíndices são encontrados, cada asterisco da fatia é substituído
pelos \linebreak componentes correspondentes que dão $n$ subíndices, que definem o
membro corrente do parâmetro.
Por exemplo, se a fatia $(a,*,1,2,*)$ está vigente e os subíndices 3 e
$b$ são encontradas no \linebreak registro subsequente, a lista completa de subíndices
usada para escolher o membro do parâmetro é $(a,3,1,2,b)$.
É permitido especificar uma fatia que não tenha asteriscos. Tal fatia, em si
própria, define uma lista completa de subíndice, em cujo caso o próximo
registro deve definir apenas um único valor do membro correspondentes do parâmetro.
Uma vez especificada uma fatia, a mesma está vigente até que apareça uma nova
fatia ou até que se encontre o fim do bloco de dados. Note que se uma fatia
não é especificada no bloco de dados, assume-se uma cujos componentes são
asteriscos em todas as posições.
\subsection{Registro plano}
O {\it registro plano} define uma lista de subíndice e um valor individual
no formato plano. Este registro possui a seguinte forma sintática:
$$\mbox{$t_1$ {\tt,} $t_2$ {\tt,} \dots {\tt,} $t_n$ {\tt,} $v$}$$
onde $t_1$, $t_2$, \dots, $t_n$ são subíndices e $v$ é um valor.
Cada subíndice, assim como o valor, pode ser um número ou um símbolo. As
vírgulas que seguem os subíndices são opcionais e podem ser omitidas.
No caso de um parâmetro ou fatia 0-dimensional, o registro plano não possui
subíndice e consiste de um valor individual apenas.
% The {\it plain data record} defines a subscript list and a single value
% in the plain format. This record has the following syntactic form:
% $$\mbox{$t_1$ {\tt,} $t_2$ {\tt,} \dots {\tt,} $t_n$ {\tt,} $v$}$$
% where $t_1$, $t_2$, \dots, $t_n$ are subscripts, and $v$ is a value.
% Each subscript as well as the value can be a number or symbol. Commae
% following subscripts are optional and may be omitted.
%
% In case of 0-dimensional parameter or slice the plain data record has
% no subscripts and consists of a single value only.
\subsection{Registro tabular}
O {\it registro tabular} define diversos valores onde cada valor é provido
de dois subíndices. Este registro possui a seguinte forma sintática:
$$\begin{array}{cccccc}
\mbox{{\tt:}}&c_1&c_2&\dots&c_n&\mbox{{\tt:=}}\\
r_1&a_{11}&a_{12}&\dots&a_{1n}&\\
r_2&a_{21}&a_{22}&\dots&a_{2n}&\\
\multicolumn{5}{c}{.\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .}&\\
r_m&a_{m1}&a_{m2}&\dots&a_{mn}&\\
\end{array}$$
onde $r_1$, $r_2$, \dots, $r_m$ são números e/ou símbolos
que correspondem a linhas da tabela; enquanto que $c_1$, $c_2$, \dots, $c_n$ são
são números e/ou símbolos que correspondem a colunas da tabela, $a_{11}$,
$a_{12}$, \dots, $a_{mn}$ são elementos da tabela. Cada elemento pode ser
um número, símbolo ou o ponto decimal ({\tt.}) individual. (neste registro,
o delimitador {\tt:} que precede a lista de colunas e o delimitador
{\tt:=} que segue após a lista de colunas, não podem ser omitidos).
Cada elemento $a_{ij}$ do bloco de dados tabulares ($1\leq i\leq m$,
$1\leq j\leq n$) define dois subíndices, onde o primeiro subíndice é
$r_i$ e o segundo é $c_j$. Estes subíndices são usados juntamente com
a fatia vigente para formar a lista completa de subíndices que identifica
um membro particular da matriz de parâmetros. Se $a_{ij}$
é um número ou um símbolo, este valor é atribuído ao membro do parâmetro.
No entanto, se $a_{ij}$ é um ponto decimal individual, o membro é atribuído
ao valor padrão especificado ou no bloco de dados do parâmetro
ou na sentença parameter, ou ainda, se nenhum valor padrão é especificado,
o membro permanece indefinido.
Uma vez que o registro tabular fornece dois subíndices para cada valor,
tanto o parâmetro quanto a fatia vigente em uso devem ser 2-dimensional.
% The {\it tabular data record} defines several values, where each value
% is provided with two subscripts. This record has the following
% syntactic form:
% $$\begin{array}{cccccc}
% \mbox{{\tt:}}&c_1&c_2&\dots&c_n&\mbox{{\tt:=}}\\
% r_1&a_{11}&a_{12}&\dots&a_{1n}&\\
% r_2&a_{21}&a_{22}&\dots&a_{2n}&\\
% \multicolumn{5}{c}{.\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .}&\\
% r_m&a_{m1}&a_{m2}&\dots&a_{mn}&\\
% \end{array}$$
% where $r_1$, $r_2$, \dots, $r_m$ are numbers and/or symbols
% corresponding to rows of the table; $c_1$, $c_2$, \dots, $c_n$ are
% numbers and/or symbols corresponding to columns of the table, $a_{11}$,
% $a_{12}$, \dots, $a_{mn}$ are table elements. Each element can be a
% number or symbol or the single decimal point ({\tt.}). (In this data
% record the delimiter {\tt:} preceding the column list and the delimiter
% {\tt:=} following the column list cannot be omitted.)
%
% Each element $a_{ij}$ of the tabular data block ($1\leq i\leq m$,
% $1\leq j\leq n$) defines two subscripts, where the first subscript is
% $r_i$, and the second one is $c_j$. These subscripts are used in
% conjunction with the current slice to form the complete subscript list
% that identifies a particular member of the parameter array. If $a_{ij}$
% is a number or symbol, this value is assigned to the parameter member.
% However, if $a_{ij}$ is the single decimal point, the member is
% assigned a default value specified either in the parameter data block
% or in the parameter statement, or, if no default value is specified,
% the member remains undefined.
%
% Since the tabular data record provides two subscripts for each value,
% either the parameter or the slice currently used should be
% 2-dimensional.
\subsection{Registro tabular transposto}
O {\it registro tabular transposto} possui a seguinte forma sintática:
$$\begin{array}{cccccc}
\mbox{{\tt(tr) :}}&c_1&c_2&\dots&c_n&\mbox{{\tt:=}}\\
r_1&a_{11}&a_{12}&\dots&a_{1n}&\\
r_2&a_{21}&a_{22}&\dots&a_{2n}&\\
\multicolumn{5}{c}{.\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .}&\\
r_m&a_{m1}&a_{m2}&\dots&a_{mn}&\\
\end{array}$$
(Neste caso, o delimitador {\tt:} que segue a palavra-chave {\tt(tr)} é
opcional e pode ser omitida.)
Este registro é completamente análogo ao registro tabular
(ver anteriormente) com a única exceção que o primeiro subíndice definido
pelo elemento $a_{ij}$ é $c_j$ enquanto que o segundo é $r_i$.
Uma vez especificado, o indicador {\tt(tr)} afeta todos registros subsequentes
até que se encontre outra fatia ou o fim do bloco de dados.
% The {\it transposed tabular data record} has the following syntactic
% form:
% $$\begin{array}{cccccc}
% \mbox{{\tt(tr) :}}&c_1&c_2&\dots&c_n&\mbox{{\tt:=}}\\
% r_1&a_{11}&a_{12}&\dots&a_{1n}&\\
% r_2&a_{21}&a_{22}&\dots&a_{2n}&\\
% \multicolumn{5}{c}{.\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .\ \ .}&\\
% r_m&a_{m1}&a_{m2}&\dots&a_{mn}&\\
% \end{array}$$
% (In this case the delimiter {\tt:} following the keyword {\tt(tr)} is
% optional and may be omitted.)
%
% This data record is completely analogous to the tabular data record
% (see above) with only exception that the first subscript defined by
% element $a_{ij}$ is $c_j$ while the second one is $r_i$.
%
% Being once specified the {\tt(tr)} indicator affects all subsequent
% data records until either a slice or the end of data block is
% encountered.
% \newpage
\subsection{Formato de dados em tabulação}
O bloco de dados do parâmetro no {\it formato tabulação} possui a seguinte
forma sintática:
$$
\begin{array}{*{8}{l}}
\multicolumn{4}{l}
{{\tt param}\ {\tt default}\ valor\ {\tt :}\ s\ {\tt :}}&
p_1\ \ \verb|,|&p_2\ \ \verb|,|&\dots\ \verb|,|&p_r\ \ \verb|:=|\\
r_{11}\ \verb|,|& r_{12}\ \verb|,|& \dots\ \verb|,|& r_{1n}\ \verb|,|&
a_{11}\ \verb|,|& a_{12}\ \verb|,|& \dots\ \verb|,|& a_{1r}\ \verb|,|\\
r_{21}\ \verb|,|& r_{22}\ \verb|,|& \dots\ \verb|,|& r_{2n}\ \verb|,|&
a_{21}\ \verb|,|& a_{22}\ \verb|,|& \dots\ \verb|,|& a_{2r}\ \verb|,|\\
\dots & \dots & \dots & \dots & \dots & \dots & \dots & \dots \\
r_{m1}\ \verb|,|& r_{m2}\ \verb|,|& \dots\ \verb|,|& r_{mn}\ \verb|,|&
a_{m1}\ \verb|,|& a_{m2}\ \verb|,|& \dots\ \verb|,|& a_{mr}\ \verb|;|\\
\end{array}
$$
1. A palavra-chave {\tt default} pode ser omitida juntamente
com o valor que a segue.
2. O nome simbólico $s$ pode ser omitido juntamente com
os dois pontos que o segue.
3. Todas as vírgulas são opcionais e podem ser omitidas.
O bloco de dados no formato tabulação mostrado acima é exatamente
equivalente aos seguintes blocos de dados:
\verb|set| $s$\ \verb|:=|\ $
\verb|(|r_{11}\verb|,|r_{12}\verb|,|\dots\verb|,|r_{1n}\verb|) |
\verb|(|r_{21}\verb|,|r_{22}\verb|,|\dots\verb|,|r_{2n}\verb|) |
\dots
\verb| (|r_{m1}\verb|,|r_{m2}\verb|,|\dots\verb|,|r_{mn}\verb|);|$
\verb|param| $p_1$\ \verb|default|\ $valor$\ \verb|:=|
$\verb| |
\verb|[|r_{11}\verb|,|r_{12}\verb|,|\dots\verb|,|r_{1n}\verb|] |a_{11}
\verb| [|r_{21}\verb|,|r_{22}\verb|,|\dots\verb|,|r_{2n}\verb|] |a_{21}
\verb| |\dots
\verb| [|r_{m1}\verb|,|r_{m2}\verb|,|\dots\verb|,|r_{mn}\verb|] |a_{m1}
\verb|;|
$
\verb|param| $p_2$\ \verb|default|\ $valor$\ \verb|:=|
$\verb| |
\verb|[|r_{11}\verb|,|r_{12}\verb|,|\dots\verb|,|r_{1n}\verb|] |a_{12}
\verb| [|r_{21}\verb|,|r_{22}\verb|,|\dots\verb|,|r_{2n}\verb|] |a_{22}
\verb| |\dots
\verb| [|r_{m1}\verb|,|r_{m2}\verb|,|\dots\verb|,|r_{mn}\verb|] |a_{m2}
\verb|;|
$
\verb| |.\ \ \ .\ \ \ .\ \ \ .\ \ \ .\ \ \ .\ \ \ .\ \ \ .\ \ \ .
\verb|param| $p_r$\ \verb|default|\ $valor$\ \verb|:=|
$\verb| |
\verb|[|r_{11}\verb|,|r_{12}\verb|,|\dots\verb|,|r_{1n}\verb|] |a_{1r}
\verb| [|r_{21}\verb|,|r_{22}\verb|,|\dots\verb|,|r_{2n}\verb|] |a_{2r}
\verb| |\dots
\verb| [|r_{m1}\verb|,|r_{m2}\verb|,|\dots\verb|,|r_{mn}\verb|] |a_{mr}
\verb|;|
$
% The parameter data block in the {\it tabbing format} has the following
% syntactic form:
% $$
% \begin{array}{*{8}{l}}
% \multicolumn{4}{l}
% {{\tt param}\ {\tt default}\ value\ {\tt :}\ s\ {\tt :}}&
% p_1\ \ \verb|,|&p_2\ \ \verb|,|&\dots\ \verb|,|&p_r\ \ \verb|:=|\\
% r_{11}\ \verb|,|& r_{12}\ \verb|,|& \dots\ \verb|,|& r_{1n}\ \verb|,|&
% a_{11}\ \verb|,|& a_{12}\ \verb|,|& \dots\ \verb|,|& a_{1r}\ \verb|,|\\
% r_{21}\ \verb|,|& r_{22}\ \verb|,|& \dots\ \verb|,|& r_{2n}\ \verb|,|&
% a_{21}\ \verb|,|& a_{22}\ \verb|,|& \dots\ \verb|,|& a_{2r}\ \verb|,|\\
% \dots & \dots & \dots & \dots & \dots & \dots & \dots & \dots \\
% r_{m1}\ \verb|,|& r_{m2}\ \verb|,|& \dots\ \verb|,|& r_{mn}\ \verb|,|&
% a_{m1}\ \verb|,|& a_{m2}\ \verb|,|& \dots\ \verb|,|& a_{mr}\ \verb|;|\\
% \end{array}
% $$
%
% 1. The keyword {\tt default} may be omitted along with a value
% following it.
%
% 2. Symbolic name $s$ may be omitted along with the colon following it.
%
% 3. All commae are optional and may be omitted.
%
% The data block in the tabbing format shown above is exactly equivalent
% to the following data blocks:
%
% \verb|set| $s$\ \verb|:=|\ $
% \verb|(|r_{11}\verb|,|r_{12}\verb|,|\dots\verb|,|r_{1n}\verb|) |
% \verb|(|r_{21}\verb|,|r_{22}\verb|,|\dots\verb|,|r_{2n}\verb|) |
% \dots
% \verb| (|r_{m1}\verb|,|r_{m2}\verb|,|\dots\verb|,|r_{mn}\verb|);|$
%
% \verb|param| $p_1$\ \verb|default|\ $value$\ \verb|:=|
%
% $\verb| |
% \verb|[|r_{11}\verb|,|r_{12}\verb|,|\dots\verb|,|r_{1n}\verb|] |a_{11}
% \verb| [|r_{21}\verb|,|r_{22}\verb|,|\dots\verb|,|r_{2n}\verb|] |a_{21}
% \verb| |\dots
% \verb| [|r_{m1}\verb|,|r_{m2}\verb|,|\dots\verb|,|r_{mn}\verb|] |a_{m1}
% \verb|;|
% $
%
% \verb|param| $p_2$\ \verb|default|\ $value$\ \verb|:=|
%
% $\verb| |
% \verb|[|r_{11}\verb|,|r_{12}\verb|,|\dots\verb|,|r_{1n}\verb|] |a_{12}
% \verb| [|r_{21}\verb|,|r_{22}\verb|,|\dots\verb|,|r_{2n}\verb|] |a_{22}
% \verb| |\dots
% \verb| [|r_{m1}\verb|,|r_{m2}\verb|,|\dots\verb|,|r_{mn}\verb|] |a_{m2}
% \verb|;|
% $
%
% \verb| |.\ \ \ .\ \ \ .\ \ \ .\ \ \ .\ \ \ .\ \ \ .\ \ \ .\ \ \ .
%
% \verb|param| $p_r$\ \verb|default|\ $value$\ \verb|:=|
%
% $\verb| |
% \verb|[|r_{11}\verb|,|r_{12}\verb|,|\dots\verb|,|r_{1n}\verb|] |a_{1r}
% \verb| [|r_{21}\verb|,|r_{22}\verb|,|\dots\verb|,|r_{2n}\verb|] |a_{2r}
% \verb| |\dots
% \verb| [|r_{m1}\verb|,|r_{m2}\verb|,|\dots\verb|,|r_{mn}\verb|] |a_{mr}
% \verb|;|
% $
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\appendix
\chapter{Usando sufixos}
\vspace*{-12pt}
Sufixos podem ser usados para recuperar valores adicionais
associados com as variáveis, restrições e objetivos do modelo.
Um {\it sufixo} consiste de um ponto ({\tt.}) seguido por uma palavra-chave
não-reservada. Por exemplo, se {\tt x} é uma variável bi-dimensional,
{\tt x[i,j].lb} é um valor numérico igual ao limite inferior da variável
elementar {\tt x[i,j]}, que (cujo valor) pode ser usado em expressões
como um parâmetro numérico.
Para as variáveis do modelo, os sufixos possuem o seguinte significado:
\begin{tabular}{@{}ll@{}}
{\tt.lb}&limite inferior (lower bound)\\
{\tt.ub}&limite superior (upper bound)\\
{\tt.status}&status na solução:\\
&0 --- indefinida\\
&1 --- básica\\
&2 --- não-básica no limite inferior\\
&3 --- não-básica no limite superior\\
&4 --- variável não-básica livre (ilimitada)\\
&5 --- variável não-básica fixa\\
{\tt.val}&valor primal na solução\\
{\tt.dual}&valor dual (custo reduzido) na solução\\
\end{tabular}
Para as restrições e objetivos do modelo, os sufixos têm os seguintes significados:
\begin{tabular}{@{}ll@{}}
{\tt.lb}&limite inferior (lower bound) da forma linear\\
{\tt.ub}&limite superior (upper bound) da forma linear\\
{\tt.status}&status na solução:\\
&0 --- indefinida\\
&1 --- não-limitante\\
&2 --- limitante no limite inferior\\
&3 --- limitante no limite superior\\
&4 --- linha limitante livre (ilimitada)\\
&5 --- restrição de igualdade limitante\\
{\tt.val}&valor primal da forma linear na solução\\
{\tt.dual}&valor dual (custo reduzido) da forma linear na solução\\
\end{tabular}
Note que os sufixos {\tt.status}, {\tt.val} e {\tt.dual} podem ser usados
apenas abaixo da sentença solve.
% Suffixes can be used to retrieve additional values associated with
% model variables, constraints, and objectives.
%
% A {\it suffix} consists of a period ({\tt.}) followed by a non-reserved
% keyword. For example, if {\tt x} is a two-dimensional variable,
% {\tt x[i,j].lb} is a numeric value equal to the lower bound of
% elemental variable {\tt x[i,j]}, which (value) can be used everywhere
% in expressions like a numeric parameter.
%
% For model variables suffixes have the following meaning:
%
% \begin{tabular}{@{}ll@{}}
% {\tt.lb}&lower bound\\
% {\tt.ub}&upper bound\\
% {\tt.status}&status in the solution:\\
% &0 --- undefined\\
% &1 --- basic\\
% &2 --- non-basic on lower bound\\
% &3 --- non-basic on upper bound\\
% &4 --- non-basic free (unbounded) variable\\
% &5 --- non-basic fixed variable\\
% {\tt.val}&primal value in the solution\\
% {\tt.dual}&dual value (reduced cost) in the solution\\
% \end{tabular}
%
% For model constraints and objectives suffixes have the following
% meaning:
%
% \begin{tabular}{@{}ll@{}}
% {\tt.lb}&lower bound of the linear form\\
% {\tt.ub}&upper bound of the linear form\\
% {\tt.status}&status in the solution:\\
% &0 --- undefined\\
% &1 --- non-active\\
% &2 --- active on lower bound\\
% &3 --- active on upper bound\\
% &4 --- active free (unbounded) row\\
% &5 --- active equality constraint\\
% {\tt.val}&primal value of the linear form in the solution\\
% {\tt.dual}&dual value (reduced cost) of the linear form in the
% solution\\
% \end{tabular}
%
% Note that suffixes {\tt.status}, {\tt.val}, and {\tt.dual} can be used
% only below the solve statement.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\chapter{Funções de data e hora}
\noindent\hfil
\begin{tabular}{c}
por Andrew Makhorin \verb|<mao@gnu.org>|\\
e Heinrich Schuchardt \verb|<heinrich.schuchardt@gmx.de>|\\
\end{tabular}
\section{Obtendo o tempo de calendário corrente}
\label{gmtime}
Para obter o tempo de calendário corrente em MathProg existe a função
{\tt gmtime}. Ela não possui argumentos e retorna o número de segundos
transcorridos desde 00:00:00 de 1{\textsuperscript{\b{o}}}
de Janeiro de 1970, pelo
Tempo Universal Coordenado (UTC). Por exemplo:
\begin{verbatim}
param utc := gmtime();
\end{verbatim}
MathProg não possui uma função para converter o tempo UTC retornado pela função
{\tt gmtime} para os tempos de calendário {\it local}. Assim, para
determinar o tempo de calendário local corrente, é preciso que adicione ao
tempo UTC retornado a diferença de horas, com respeito a UTC, expressa em
segundos. Por exemplo, a hora em Berlim durante o inverno é uma hora à frente
do UTC, que corresponde a uma diferença horária de +1~hora~= +3600~segundos,
assim, o tempo de calendário corrente no inverno em Berlim pode ser determinado
como segue:
\begin{verbatim}
param now := gmtime() + 3600;
\end{verbatim}
\noindent De forma análoga, o horário de verão em Chicago (Zona Horária Central-CDT)
é cinco horas atrás da UTC, de modo que o horário corrente do calendário local
pode ser determinado como segue:
\begin{verbatim}
param now := gmtime() - 5 * 3600;
\end{verbatim}
Note que o valor retornado por {\tt gmtime} é volátil, i.e., ao ser
chamada diversas vezes, esta função pode retornar diferentes valores.
% \noindent\hfil
% \begin{tabular}{c}
% by Andrew Makhorin \verb|<mao@gnu.org>|\\
% and Heinrich Schuchardt \verb|<heinrich.schuchardt@gmx.de>|\\
% \end{tabular}
%
% \section{Obtaining current calendar time}
% \label{gmtime}
%
% To obtain the current calendar time in MathProg there exists the
% function {\tt gmtime}. It has no arguments and returns the number of
% seconds elapsed since 00:00:00 on January 1, 1970, Coordinated
% Universal Time (UTC). For example:
%
% \begin{verbatim}
% param utc := gmtime();
% \end{verbatim}
%
% MathProg has no function to convert UTC time returned by the function
% {\tt gmtime} to {\it local} calendar times. Thus, if you need to
% determine the current local calendar time, you have to add to the UTC
% time returned the time offset from UTC expressed in seconds. For
% example, the time in Berlin during the winter is one hour ahead of UTC
% that corresponds to the time offset +1~hour~= +3600~secs, so the
% current winter calendar time in Berlin may be determined as follows:
%
% \begin{verbatim}
% param now := gmtime() + 3600;
% \end{verbatim}
%
% \noindent Similarly, the summer time in Chicago (Central Daylight Time)
% is five hours behind UTC, so the corresponding current local calendar
% time may be determined as follows:
%
% \begin{verbatim}
% param now := gmtime() - 5 * 3600;
% \end{verbatim}
%
% Note that the value returned by {\tt gmtime} is volatile, i.e. being
% called several times this function may return different values.
\section{Convertendo cadeia de caracteres ao tempo de calendário}
\label{str2time}
A função {\tt str2time(}{\it s}{\tt,} {\it f}{\tt)} converte uma
cadeia de caractere (impressão da data e hora) \linebreak especificada pelo seu
primeiro argumento {\it s}, que deve ser uma expressão simbólica,
para o tempo de calendário apropriado para cálculos aritméticos.
A conversão é controlada pela cadeia de formato especificado {\it f}
(o segundo argumento), que também deve ser uma expressão simbólica.
% The function {\tt str2time(}{\it s}{\tt,} {\it f}{\tt)} converts a
% character string (timestamp) specified by its first argument {\it s},
% which should be a symbolic expression, to the calendar time suitable
% for arithmetic calculations. The conversion is controlled by the
% specified format string {\it f} (the second argument), which also
% should be a symbolic expression.
% \newpage
A conversão resultante retornada por {\tt str2time} possui o mesmo significado
dos valores retornados pela função {\tt gmtime} (ver Subseção
\ref{gmtime}, página \pageref{gmtime}). Note que {\tt str2time}
{\tt não corrige} o tempo de calendário retornado para zona horária local,
i.e., ao se aplicar a 00:00:00 de 1{\textsuperscript{\b{o}}}
de Janeiro de 1970, ela sempre retorna 0.
% The result of conversion returned by {\tt str2time} has the same
% meaning as values returned by the function {\tt gmtime} (see Subsection
% \ref{gmtime}, page \pageref{gmtime}). Note that {\tt str2time} does
% {\tt not} correct the calendar time returned for the local timezone,
% i.e. being applied to 00:00:00 on January 1, 1970 it always returns 0.
Por exemplo, as sentenças de modelo:
\begin{verbatim}
param s, symbolic, := "07/14/98 13:47";
param t := str2time(s, "%m/%d/%y %H:%M");
display t;
\end{verbatim}
\noindent produz a seguinte saída:
\begin{verbatim}
t = 900424020
\end{verbatim}
\noindent onde o tempo de calendário impresso corresponde a 13:47:00 em
14 de Julho de 1998.
A cadeia de formato passada à função {\tt str2time} consiste de
especificadores de conversão e caracteres ordinários. Cada especificador de
conversão inicia com um caractere de porcentagem ({\tt\%}) seguido de
uma letra.
Os seguintes especificadores de conversão podem ser usados na cadeia de formato:
\begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
{\tt\%b}&O nome do mês abreviado (insensível a maiúsculas). Pelo menos as três
primeiras letras do mês devem aparecer na cadeia de entrada.\\
\end{tabular}
\begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
{\tt\%d}&O dia do mês como número decimal (de 1 até 31).
Se permite o zero como primeiro dígito, embora não seja necessário.\\
\end{tabular}
\begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
{\tt\%h}&O mesmo que {\tt\%b}.\\
\end{tabular}
\begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
{\tt\%H}&A hora como um número decimal, usando um relógio de 24-horas (de 0
a 23). Se permite o zero como primeiro dígito, embora não seja necessário.\\
\end{tabular}
\begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
{\tt\%m}&O mês como um número decimal (de 1 a 12).
Se permite o zero como primeiro dígito, embora não seja necessário.\\
\end{tabular}
\begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
{\tt\%M}&O minuto como um número decimal (de 0 a 59).
Se permite o zero como primeiro dígito, embora não seja necessário.\\
\end{tabular}
\begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
{\tt\%S}&O segundo como um número decimal (de 0 to 60).
Se permite o zero como primeiro dígito, embora não seja necessário.\\
\end{tabular}
\begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
{\tt\%y}&O ano sem o século, como um número decimal (de 0 to 99).
Se permite o zero como primeiro dígito, embora não seja necessário.
Valores de entrada de 0 a 68 são considerados dos anos 2000 a 2068
enquanto que os valores 69 até 99 como dos anos 1969 to 1999.\\
\end{tabular}
\begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
{\tt\%z}&A diferença horária do GMT no formato ISO 8601.\\
\end{tabular}
\begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
{\tt\%\%}&Um caractere {\tt\%} literal.\\
\end{tabular}
Todos os outros caracteres (ordinários) na cadeia de formato devem ter um
caractere \linebreak correspondente com a cadeia de entrada a ser convertida. Exceções
são espaços na cadeia de entrada, a qual pode coincidir com zero ou mais
caracteres de espaço na cadeia de formato.
% For example, the model statements:
%
% \begin{verbatim}
% param s, symbolic, := "07/14/98 13:47";
% param t := str2time(s, "%m/%d/%y %H:%M");
% display t;
% \end{verbatim}
%
% \noindent produce the following printout:
%
% \begin{verbatim}
% t = 900424020
% \end{verbatim}
%
% \noindent where the calendar time printed corresponds to 13:47:00 on
% July 14, 1998.
%
% The format string passed to the function {\tt str2time} consists of
% conversion specifiers and ordinary characters. Each conversion
% specifier begins with a percent ({\tt\%}) character followed by a
% letter.
%
% The following conversion specifiers may be used in the format string:
%
% \begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
% {\tt\%b}&The abbreviated month name (case insensitive). At least three
% first letters of the month name should appear in the input string.\\
% \end{tabular}
%
% \begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
% {\tt\%d}&The day of the month as a decimal number (range 1 to 31).
% Leading zero is permitted, but not required.\\
% \end{tabular}
%
% \begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
% {\tt\%h}&The same as {\tt\%b}.\\
% \end{tabular}
%
% \begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
% {\tt\%H}&The hour as a decimal number, using a 24-hour clock (range 0
% to 23). Leading zero is permitted, but not required.\\
% \end{tabular}
%
% \begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
% {\tt\%m}&The month as a decimal number (range 1 to 12). Leading zero is
% permitted, but not required.\\
% \end{tabular}
%
% \begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
% {\tt\%M}&The minute as a decimal number (range 0 to 59). Leading zero
% is permitted, but not required.\\
% \end{tabular}
%
% \begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
% {\tt\%S}&The second as a decimal number (range 0 to 60). Leading zero
% is permitted, but not required.\\
% \end{tabular}
%
% \begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
% {\tt\%y}&The year without a century as a decimal number (range 0 to 99).
% Leading zero is permitted, but not required. Input values in the range
% 0 to 68 are considered as the years 2000 to 2068 while the values 69 to
% 99 as the years 1969 to 1999.\\
% \end{tabular}
%
% \begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
% {\tt\%z}&The offset from GMT in ISO 8601 format.\\
% \end{tabular}
%
% \begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
% {\tt\%\%}&A literal {\tt\%} character.\\
% \end{tabular}
%
% All other (ordinary) characters in the format string should have a
% matching character in the input string to be converted. Exceptions are
% spaces in the input string which can match zero or more space
% characters in the format string.
% \newpage
Se algum componente de data e/ou hora estão ausentes no formato e,
portanto, na cadeia de entrada, a função {\tt str2time} usa seus valores
padrão correspondendo a 00:00:00 de 1{\textsuperscript{\b{o}}}
de Janeiro de 1970, ou seja, o valor padrão para o ano é 1970, o valor
padrão para o mês é Janeiro, etc.
A função {\tt str2time} é aplicável a todos horários calendário desde
00:00:00 de 1{\textsuperscript{\b{o}}} de Janeiro de 0001 até 23:59:59
de 31 de Dezembro de 4000 do calendário Gregoriano.
% If some date and/or time component(s) are missing in the format and,
% therefore, in the input string, the function {\tt str2time} uses their
% default values corresponding to 00:00:00 on January 1, 1970, that is,
% the default value of the year is 1970, the default value of the month
% is January, etc.
%
% The function {\tt str2time} is applicable to all calendar times in the
% range 00:00:00 on January 1, 0001 to 23:59:59 on December 31, 4000 of
% the Gregorian calendar.
\section{Convertendo tempo de calendário a uma cadeia de caracteres}
\label{time2str}
A função {\tt time2str(}{\it t}{\tt,} {\it f}{\tt)} converte o tempo
de calendário especificado pelo seu primeiro \linebreak argumento {\it t}, que
deve ser uma expressão numérica, para uma cadeia de caracteres
(valor \linebreak simbólico). A conversão é controlada pela cadeia de formato
{\it f} (o segundo argumento), que deve ser uma expressão numérica.
O tempo de calendário passado para {\tt time2str} possui o mesmo
significado dos valores retornados pela função {\tt gmtime} (ver Subseção
\ref{gmtime}, página \pageref{gmtime}). Note que {\tt time2str}
{\it não corrige} o tempo de calendário especificado para zona horária local,
i.e., o tempo de calendário 0 sempre corresponde a 00:00:00 de
1{\textsuperscript{\b{o}}} de Janeiro de 1970.
Por exemplo, as sentenças de modelo:
\begin{verbatim}
param s, symbolic, := time2str(gmtime(), "%FT%TZ");
display s;
\end{verbatim}
\noindent pode produzir a seguinte impressão:
\begin{verbatim}
s = '2008-12-04T00:23:45Z'
\end{verbatim}
\noindent que é a impressão da data e hora no formato ISO.
A cadeia de formato passada para a função {\tt time2str} consiste de
especificadores de conversão e caracteres ordinários. Cada especificador
de conversão começa com um caractere de porcentagem ({\tt\%}) seguido
de uma letra.
Os seguintes especificadores de conversão podem ser usados na cadeia de formato:
\begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
{\tt\%a}&O nome do dia da semana abreviado(2 caracteres).\\
\end{tabular}
\begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
{\tt\%A}&O nome do dia da semana completo.\\
\end{tabular}
\begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
{\tt\%b}&O nome do dia do mês abreviado (3 caracteres).\\
\end{tabular}
\begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
{\tt\%B}&O nome do mês completo.\\
\end{tabular}
\begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
{\tt\%C}&O século do ano, ou seja, o maior inteiro não maior que o
ano dividido por~100.\\
\end{tabular}
\begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
{\tt\%d}&O dia do mês como um número decimal (de 01 até 31).\\
\end{tabular}
\begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
{\tt\%D}&A data usando o formato \verb|%m/%d/%y|.\\
\end{tabular}
\begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
{\tt\%e}&O dia do mês, como em \verb|%d|, mas preenchido com espaço
em branco ao invés de zero.\\
\end{tabular}
\begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
{\tt\%F}&A data usando o formato \verb|%Y-%m-%d|.\\
\end{tabular}
\begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
{\tt\%g}&O ano correspondente ao número de semana ISO, mas sem o século
(de 00 até~99). Este possui o mesmo formato e valor que \verb|%y|,
exceto que se o número de semana ISO (ver \verb|%V|) pertence
ao ano anterior ou seguinte, se usa aquele ano em seu lugar.\\
\end{tabular}
\begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
{\tt\%G}&O ano correspondente ao número de semana ISO.
Este possui o mesmo formato e valor que \verb|%Y|,
exceto que se o número de semana ISO (ver \verb|%V|) pertence
ao ano anterior ou seguinte, se usa aquele ano em seu lugar.\\
\end{tabular}
\begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
{\tt\%h}&O mesmo que \verb|%b|.\\
\end{tabular}
\begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
{\tt\%H}&A hora como um número decimal usando um relógio 24 horas (de 00 até 23).\\
\end{tabular}
\begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
{\tt\%I}&A hora como um número decimal usando um relógio 12 horas (de 01 até 12).\\
\end{tabular}
\begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
{\tt\%j}&O dia do ano como um número decimal (de 001 até 366).\\
\end{tabular}
\begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
{\tt\%k}&A hora como um número decimal usando um relógio 24 horas, como
\verb|%H|, mas preenchido com espaço em branco ao invés de zero.\\
\end{tabular}
\begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
{\tt\%l}&A hora como um número decimal usando um relógio 12 horas, como
\verb|%I|, mas preenchido com espaço em branco ao invés de zero.
\end{tabular}
\begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
{\tt\%m}&O mês como um número decimal (de 01 até 12).\\
\end{tabular}
\begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
{\tt\%M}&O minuto como um número decimal (de 00 até 59).\\
\end{tabular}
\begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
{\tt\%p}&Tanto {\tt AM} como {\tt PM}, de acordo com o valor da hora fornecido.
Meia-noite é tratada como {\tt AM} e meio-dia, como {\tt PM}.\\
\end{tabular}
\begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
{\tt\%P}&Tanto {\tt am} como {\tt pm}, de acordo com o valor da hora fornecido.
Meia-noite é tratada como {\tt am} e meio-dia, como {\tt pm}.\\
\end{tabular}
\begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
{\tt\%R}&A hora e minuto em números decimais usando o formato
\verb|%H:%M|.\\
\end{tabular}
\begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
{\tt\%S}&O segundo como um número decimal (de 00 até 59).\\
\end{tabular}
\begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
{\tt\%T}&A hora do dia em números decimais usando o formato
\verb|%H:%M:%S|.\\
\end{tabular}
\begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
{\tt\%u}&O dia da semana como número decimal (de 1 até 7) em que Segunda
é 1.\\
\end{tabular}
\begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
{\tt\%U}&O número da semana do ano corrente como um número decimal (de
00 até 53) iniciando com o primeiro Domingo como o primeiro dia da
primeira semana. Os dias que precedem o primeiro Domingo do ano são
considerados parte da semana 00.
\end{tabular}
\begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
{\tt\%V}&O número da semana ISO como um número decimal (de 01 até 53).
Semanas ISO iniciam com Segunda e finalizam com Domingo.
A semana 01 de um ano é a primeira semana que possui a maioria de
seus dias naquele ano. Isto é equivalente à semana contendo 4 de
Janeiro. A semana 01 de um ano pode conter dias do ano anterior.
A semana anterior à semana 01 de um ano é a última semana
(52 ou 53) do ano anterior, mesmo se ela contém dias do novo ano.
Em outras palavras, se 1{\textsuperscript{\b{o}}} de Janeiro
é Segunda, Terça, Quarta ou Quinta, ele está na semana 01;
Se 1{\textsuperscript{\b{o}}} de Janeiro é Sexta,
Sábado ou Domingo, ele está na semana 52 ou 53 do ano anterior.\\
\end{tabular}
\begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
{\tt\%w}&O dia da semana como um número decimal (de 0 até 6) em que Domingo
é 0.\\
\end{tabular}
\begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
{\tt\%W}&O número da semana do ano corrente como um número decimal (de
00 até 53), iniciando com a primeira Segunda como o primeiro dia da primeira
semana. Dias que precedem a primeira Segunda do ano são considerados parte
da semana 00.\\
\end{tabular}
\begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
{\tt\%y}&O ano sem o século como um número decimal (de 00 até
99), ou seja, o ano \verb|mod|~100.\\
\end{tabular}
\begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
{\tt\%Y}&O ano como um número decimal, usando o calendário Gregoriano.\\
\end{tabular}
\begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
{\tt\%\%}&Um caractere \verb|%| literal.\\
\end{tabular}
Todos os outros caracteres (ordinários) na cadeia de formato são simplesmente copiados
à cadeia resultante.
O primeiro argumento (tempo do calendário) passado para a função {\tt time2str}
deve estar entre $-62135596800$ até $+64092211199$, o que corresponde ao período
de 00:00:00 de 1{\textsuperscript{\b{o}}} de Janeiro de 0001 até 23:59:59
de 31 de Dezembro de 4000 do calendário Gregoriano.
% The function {\tt time2str(}{\it t}{\tt,} {\it f}{\tt)} converts the
% calendar time specified by its first argument {\it t}, which should be
% a numeric expression, to a character string (symbolic value). The
% conversion is controlled by the specified format string {\it f} (the
% second argument), which should be a symbolic expression.
%
% The calendar time passed to {\tt time2str} has the same meaning as
% values returned by the function {\tt gmtime} (see Subsection
% \ref{gmtime}, page \pageref{gmtime}). Note that {\tt time2str} does
% {\it not} correct the specified calendar time for the local timezone,
% i.e. the calendar time 0 always corresponds to 00:00:00 on January 1,
% 1970.
%
% For example, the model statements:
%
% \begin{verbatim}
% param s, symbolic, := time2str(gmtime(), "%FT%TZ");
% display s;
% \end{verbatim}
%
% \noindent may produce the following printout:
%
% \begin{verbatim}
% s = '2008-12-04T00:23:45Z'
% \end{verbatim}
%
% \noindent which is a timestamp in the ISO format.
%
% The format string passed to the function {\tt time2str} consists of
% conversion specifiers and ordinary characters. Each conversion
% specifier begins with a percent ({\tt\%}) character followed by a
% letter.
%
% The following conversion specifiers may be used in the format string:
%
% \begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
% {\tt\%a}&The abbreviated (2-character) weekday name.\\
% \end{tabular}
%
% \begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
% {\tt\%A}&The full weekday name.\\
% \end{tabular}
%
% \begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
% {\tt\%b}&The abbreviated (3-character) month name.\\
% \end{tabular}
%
% \begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
% {\tt\%B}&The full month name.\\
% \end{tabular}
%
% \begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
% {\tt\%C}&The century of the year, that is the greatest integer not
% greater than the year divided by~100.\\
% \end{tabular}
%
% \begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
% {\tt\%d}&The day of the month as a decimal number (range 01 to 31).\\
% \end{tabular}
%
% \begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
% {\tt\%D}&The date using the format \verb|%m/%d/%y|.\\
% \end{tabular}
%
% \begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
% {\tt\%e}&The day of the month like with \verb|%d|, but padded with
% blank rather than zero.\\
% \end{tabular}
%
% \begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
% {\tt\%F}&The date using the format \verb|%Y-%m-%d|.\\
% \end{tabular}
%
% \begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
% {\tt\%g}&The year corresponding to the ISO week number, but without the
% century (range 00 to~99). This has the same format and value as
% \verb|%y|, except that if the ISO week number (see \verb|%V|) belongs
% to the previous or next year, that year is used instead.\\
% \end{tabular}
%
% \begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
% {\tt\%G}&The year corresponding to the ISO week number. This has the
% same format and value as \verb|%Y|, except that if the ISO week number
% (see \verb|%V|) belongs to the previous or next year, that year is used
% instead.
% \end{tabular}
%
% \begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
% {\tt\%h}&The same as \verb|%b|.\\
% \end{tabular}
%
% \begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
% {\tt\%H}&The hour as a decimal number, using a 24-hour clock (range 00
% to 23).\\
% \end{tabular}
%
% \begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
% {\tt\%I}&The hour as a decimal number, using a 12-hour clock (range 01
% to 12).\\
% \end{tabular}
%
% \begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
% {\tt\%j}&The day of the year as a decimal number (range 001 to 366).\\
% \end{tabular}
%
% \begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
% {\tt\%k}&The hour as a decimal number, using a 24-hour clock like
% \verb|%H|, but padded with blank rather than zero.\\
% \end{tabular}
%
% \begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
% {\tt\%l}&The hour as a decimal number, using a 12-hour clock like
% \verb|%I|, but padded with blank rather than zero.
% \end{tabular}
%
% \begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
% {\tt\%m}&The month as a decimal number (range 01 to 12).\\
% \end{tabular}
%
% \begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
% {\tt\%M}&The minute as a decimal number (range 00 to 59).\\
% \end{tabular}
%
% \begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
% {\tt\%p}&Either {\tt AM} or {\tt PM}, according to the given time value.
% Midnight is treated as {\tt AM} and noon as {\tt PM}.\\
% \end{tabular}
%
% \begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
% {\tt\%P}&Either {\tt am} or {\tt pm}, according to the given time value.
% Midnight is treated as {\tt am} and noon as {\tt pm}.\\
% \end{tabular}
%
% \begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
% {\tt\%R}&The hour and minute in decimal numbers using the format
% \verb|%H:%M|.\\
% \end{tabular}
%
% \begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
% {\tt\%S}&The second as a decimal number (range 00 to 59).\\
% \end{tabular}
%
% \begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
% {\tt\%T}&The time of day in decimal numbers using the format
% \verb|%H:%M:%S|.\\
% \end{tabular}
%
% \begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
% {\tt\%u}&The day of the week as a decimal number (range 1 to 7), Monday
% being 1.\\
% \end{tabular}
%
% \begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
% {\tt\%U}&The week number of the current year as a decimal number (range
% 00 to 53), starting with the first Sunday as the first day of the first
% week. Days preceding the first Sunday in the year are considered to be
% in week 00.
% \end{tabular}
%
% \begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
% {\tt\%V}&The ISO week number as a decimal number (range 01 to 53). ISO
% weeks start with Monday and end with Sunday. Week 01 of a year is the
% first week which has the majority of its days in that year; this is
% equivalent to the week containing January 4. Week 01 of a year can
% contain days from the previous year. The week before week 01 of a year
% is the last week (52 or 53) of the previous year even if it contains
% days from the new year. In other word, if 1 January is Monday, Tuesday,
% Wednesday or Thursday, it is in week 01; if 1 January is Friday,
% Saturday or Sunday, it is in week 52 or 53 of the previous year.\\
% \end{tabular}
%
% \begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
% {\tt\%w}&The day of the week as a decimal number (range 0 to 6), Sunday
% being 0.\\
% \end{tabular}
%
% \begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
% {\tt\%W}&The week number of the current year as a decimal number (range
% 00 to 53), starting with the first Monday as the first day of the first
% week. Days preceding the first Monday in the year are considered to be
% in week 00.\\
% \end{tabular}
%
% \begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
% {\tt\%y}&The year without a century as a decimal number (range 00 to
% 99), that is the year modulo~100.\\
% \end{tabular}
%
% \begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
% {\tt\%Y}&The year as a decimal number, using the Gregorian calendar.\\
% \end{tabular}
%
% \begin{tabular}{@{}p{20pt}p{421.5pt}@{}}
% {\tt\%\%}&A literal \verb|%| character.\\
% \end{tabular}
%
% All other (ordinary) characters in the format string are simply copied
% to the resultant string.
%
% The first argument (calendar time) passed to the function {\tt time2str}
% should be in the range from $-62135596800$ to $+64092211199$ that
% corresponds to the period from 00:00:00 on January 1, 0001 to 23:59:59
% on December 31, 4000 of the Gregorian calendar.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\chapter{Controladores de tabelas}
\label{drivers}
\noindent\hfil
\begin{tabular}{c}
por Andrew Makhorin \verb|<mao@gnu.org>|\\
e Heinrich Schuchardt \verb|<heinrich.schuchardt@gmx.de>|\\
\end{tabular}
\bigskip\bigskip
O {\it controlador de tabelas} é um módulo do programa que permite transmitir
dados entre objetos de um modelo MathProg e tabela de dados.
Atualmente, o pacote GLPK possui quatro controladores de tabelas:
\vspace*{-8pt}
\begin{itemize}
\item controlador interno de tabelas CSV;
\item controlador interno de tabelas xBASE;
\item controlador de tabelas ODBC;
\item controlador de tabelas MySQL.
\end{itemize}
% The {\it table driver} is a program module which provides transmitting
% data between MathProg model objects and data tables.
%
% Currently the GLPK package has four table drivers:
%
% \vspace*{-8pt}
%
% \begin{itemize}
% \item built-in CSV table driver;
% \item built-in xBASE table driver;
% \item ODBC table driver;
% \item MySQL table driver.
% \end{itemize}
\vspace*{-8pt}
\section{Controlador de tabelas CSV}
O controlador de tabelas CSV assume que a tabela de dados está representada
na forma de \linebreak arquivo de texto plano, em formato de arquivo CSV
(valores serparados por vígula: \linebreak comma-separated values) como descrito
abaixo.
Para escolher o controlador de tabelas CSV, seu nome na sentença table deve ser
especificado como \verb|"CSV"| e o único argumento deve especificar o nome do
arquivo de texto plano contendo a tabela. Por exemplo:
\begin{verbatim}
table dados IN "CSV" "dados.csv": ... ;
\end{verbatim}
O sufixo do nome do arquivo pode ser arbitrário, no entanto,
é recomendado usar o sufixo `\verb|.csv|'.
Ao ler tabelas de entrada o controlador de tabelas CSV fornece um campo
implícito chamado \verb|RECNO|, que contém o número do registro corrente.
Este campo pode ser especificado na sentença de entrada table, como
se realmente houvesse um campo chamado \verb|RECNO| no arquivo CSV. Por exemplo:
\begin{verbatim}
table lista IN "CSV" "lista.csv": num <- [RECNO], ... ;
\end{verbatim}
% The CSV table driver assumes that the data table is represented in the
% form of a plain text file in the CSV (comma-separated values) file
% format as described below.
%
% To choose the CSV table driver its name in the table statement should
% be specified as \verb|"CSV"|, and the only argument should specify the
% name of a plain text file containing the table. For example:
%
% \begin{verbatim}
% table data IN "CSV" "data.csv": ... ;
% \end{verbatim}
%
% The filename suffix may be arbitrary, however, it is recommended to use
% the suffix `\verb|.csv|'.
%
% On reading input tables the CSV table driver provides an implicit field
% named \verb|RECNO|, which contains the current record number. This
% field can be specified in the input table statement as if there were
% the actual field named \verb|RECNO| in the CSV file. For example:
%
% \begin{verbatim}
% table list IN "CSV" "list.csv": num <- [RECNO], ... ;
% \end{verbatim}
\newpage
\subsection*{Formato CSV\footnote{Este material é baseado no documento RFC
4180.}}
O formato CSV (\textit{comma-separated values}) é um formato de arquivo de texto plano
definido como segue.
1. Cada registro é localizado em uma linha separada, delimitada por uma quebra de linha. Por exemplo:
\begin{verbatim}
aaa,bbb,ccc\n
xxx,yyy,zzz\n
\end{verbatim}
\noindent
onde \verb|\n| significa o caractere de controle \verb|LF| ({\tt 0x0A}).
2. O último registro no arquivo pode ou não ter a quebra de linha. Por exemplo:
\begin{verbatim}
aaa,bbb,ccc\n
xxx,yyy,zzz
\end{verbatim}
3. Deve haver uma linha de cabeçalho na primeira linha do arquivo no
mesmo formato das linhas de registros normais. Este cabeçalho deve
conter nomes correspondendo aos campos no arquivo. O número de nomes
de campos na linha de cabeçalho deve ser o mesmo do número de campos
dos registros do arquivo. Por exemplo:
\begin{verbatim}
nome1,nome2,nome3\n
aaa,bbb,ccc\n
xxx,yyy,zzz\n
\end{verbatim}
4. Dentro do cabeçalho e de cada registro, podem haver um ou mais campos
separados por vírgulas. Cada linha deve conter o mesmo número de campos
por todos arquivo. Espaços são considerados parte de um campo, portanto,
não são ignorados. O último campo do registro não deve ser seguido de
vírgula. Por exemplo:
\begin{verbatim}
aaa,bbb,ccc\n
\end{verbatim}
5. Campos podem ou não estar cercados em aspas duplas. Por exemplo:
\begin{verbatim}
"aaa","bbb","ccc"\n
zzz,yyy,xxx\n
\end{verbatim}
6. Se um campo é cercado de aspas duplas, cada aspa dupla que faça
parte do campo deve ser codificado duas vezes. Por exemplo:
\begin{verbatim}
"aaa","b""bb","ccc"\n
\end{verbatim}
\para{Exemplo}
\begin{verbatim}
DE,PARA,DISTANCIA,CUSTO
Seattle,New-York,2.5,0.12
Seattle,Chicago,1.7,0.08
Seattle,Topeka,1.8,0.09
San-Diego,New-York,2.5,0.15
San-Diego,Chicago,1.8,0.10
San-Diego,Topeka,1.4,0.07
\end{verbatim}
% The CSV (comma-separated values) format is a plain text file format
% defined as follows.
%
% 1. Each record is located on a separate line, delimited by a line
% break. For example:
%
% \begin{verbatim}
% aaa,bbb,ccc\n
% xxx,yyy,zzz\n
% \end{verbatim}
%
% \noindent
% where \verb|\n| means the control character \verb|LF| ({\tt 0x0A}).
%
% 2. The last record in the file may or may not have an ending line
% break. For example:
%
% \begin{verbatim}
% aaa,bbb,ccc\n
% xxx,yyy,zzz
% \end{verbatim}
%
% 3. There should be a header line appearing as the first line of the
% file in the same format as normal record lines. This header should
% contain names corresponding to the fields in the file. The number of
% field names in the header line should be the same as the number of
% fields in the records of the file. For example:
%
% \begin{verbatim}
% name1,name2,name3\n
% aaa,bbb,ccc\n
% xxx,yyy,zzz\n
% \end{verbatim}
%
% 4. Within the header and each record there may be one or more fields
% separated by commas. Each line should contain the same number of fields
% throughout the file. Spaces are considered as part of a field and
% therefore not ignored. The last field in the record should not be
% followed by a comma. For example:
%
% \begin{verbatim}
% aaa,bbb,ccc\n
% \end{verbatim}
%
% 5. Fields may or may not be enclosed in double quotes. For example:
%
% \begin{verbatim}
% "aaa","bbb","ccc"\n
% zzz,yyy,xxx\n
% \end{verbatim}
%
% 6. If a field is enclosed in double quotes, each double quote which is
% part of the field should be coded twice. For example:
%
% \begin{verbatim}
% "aaa","b""bb","ccc"\n
% \end{verbatim}
%
% \para{Example}
%
% \begin{verbatim}
% FROM,TO,DISTANCE,COST
% Seattle,New-York,2.5,0.12
% Seattle,Chicago,1.7,0.08
% Seattle,Topeka,1.8,0.09
% San-Diego,New-York,2.5,0.15
% San-Diego,Chicago,1.8,0.10
% San-Diego,Topeka,1.4,0.07
% \end{verbatim}
\newpage
\section{Controlador de tabelas xBASE}
O controlador de tabelas xBASE assume que a tabela de dados é armazenada no
formato de arquivo .dbf.
Para escolher o controlador de tabela xBASE, seu nome na sentença table deve ser
especificado como \verb|"xBASE"| e o primeiro argumento deve especificar o nome
de um arquivo .dbf contendo a tabela. Para a tabela de saída deve haver um
segundo argumento definindo o formato da tabela na forma
\verb|"FF...F"|, onde \verb|F| é tanto {\tt C({\it n})},
que especifica um campo de caractere de tamanho $n$, ou
{\tt N({\it n}{\rm [},{\it p}{\rm ]})}, que especifica um campo numérico
de tamanho $n$ e precisão $p$ (por padrão $p$ é 0).
Adiante está um simples exemplo que ilustra a criação e leitura de um arquivo .dbf:
\begin{verbatim}
table tab1{i in 1..10} OUT "xBASE" "foo.dbf"
"N(5)N(10,4)C(1)C(10)": 2*i+1 ~ B, Uniform(-20,+20) ~ A,
"?" ~ FOO, "[" & i & "]" ~ C;
set S, dimen 4;
table tab2 IN "xBASE" "foo.dbf": S <- [B, C, RECNO, A];
display S;
end;
\end{verbatim}
% The xBASE table driver assumes that the data table is stored in the
% .dbf file format.
%
% To choose the xBASE table driver its name in the table statement should
% be specified as \verb|"xBASE"|, and the first argument should specify
% the name of a .dbf file containing the table. For the output table there
% should be the second argument defining the table format in the form
% \verb|"FF...F"|, where \verb|F| is either {\tt C({\it n})},
% which specifies a character field of length $n$, or
% {\tt N({\it n}{\rm [},{\it p}{\rm ]})}, which specifies a numeric field
% of length $n$ and precision $p$ (by default $p$ is 0).
%
% The following is a simple example which illustrates creating and
% reading a .dbf file:
%
% \begin{verbatim}
% table tab1{i in 1..10} OUT "xBASE" "foo.dbf"
% "N(5)N(10,4)C(1)C(10)": 2*i+1 ~ B, Uniform(-20,+20) ~ A,
% "?" ~ FOO, "[" & i & "]" ~ C;
% set S, dimen 4;
% table tab2 IN "xBASE" "foo.dbf": S <- [B, C, RECNO, A];
% display S;
% end;
% \end{verbatim}
\section{Controlador de tabelas ODBC}
O controlador de tabelas ODBC permite conexões com bancos de dados SQL usando
uma \linebreak implementação da interface ODBC baseada na Call Level Interface
(CLI).\footnote{A norma software correspondente é definida na
ISO/IEC 9075-3:2003.}
\para{Debian GNU/Linux.}
No Debian GNU/Linux o controlador de tabelas ODBC usa o pacote iODBC,
\footnote{Ver {\tt<http://www.iodbc.org/>}.} que deve ser instalado antes
de montar o pacote GLPK. A instalação pode ser efetuada com o seguinte
comando:
\begin{verbatim}
sudo apt-get install libiodbc2-dev
\end{verbatim}
Note que, ao configurar o pacote GLPK, para habilitar o uso da biblioteca do iODBC
a opção `\verb|--enable-odbc|' deve ser passada para o script de configuração.
Para seu uso em todo sistema, as bases de dados individuais devem ser inseridas em
\verb|/etc/odbc.ini| e \verb|/etc/odbcinst.ini|. As conexões das bases de dados
a serem usadas por um único usuário são especificadas por arquivos do diretório
home (\verb|.odbc.ini| e \verb|.odbcinst.ini|).
\para{Microsoft Windows.}
No Microsoft Windows o controlador de tabelas ODBC usa a biblioteca Microsoft ODBC.
Para habilitar esta funcionalidade, o símbolo:
\begin{verbatim}
#define ODBC_DLNAME "odbc32.dll"
\end{verbatim}
\noindent
deve ser definido no arquivo de configuração do GLPK `\verb|config.h|'.
Fontes de dados podem ser criados via Ferramentas Administrativas do
Painel de Controle.
Para escolher do controlador de tabelas ODBC, seu nome na sentença table deve
ser especificado como \verb|'ODBC'| ou \verb|'iODBC'|.
% \newpage
A lista de argumentos é especificada como segue.
O primeiro argumento é a cadeia de conexão passada para a biblioteca ODBC,
por exemplo:
\verb|'DSN=glpk;UID=user;PWD=password'|, ou
\verb|'DRIVER=MySQL;DATABASE=glpkdb;UID=user;PWD=password'|.
Diferentes partes da cadeia são separadas por ponto e vírgula. Cada parte
consiste de um par {\it nome-do-campo} e {\it valor} separados pelo sinar
de igualdade. Os nomes de campo permitidos dependem da biblioteca ODBC.
Tipicamente os seguintes nomes-de-campo são permitidos:
\verb|DATABASE | base de dados;
\verb|DRIVER | controlador ODBC;
\verb|DSN | nome de uma fonte de dados;
\verb|FILEDSN | nome de um arquivo de fonte de dados;
\verb|PWD | senha de usuário;
\verb|SERVER | base de dados;
\verb|UID | nome de usuário.
O segundo argumento e todos os seguintes são considerados como
sentenças SQL.
As sentenças SQL podem ser estendidas sobre múltiplos argumentos. Se o
último caractere de um argumento é um ponto e vírgula, este indica
o fim de uma sentença SQL.
Os argumentos de uma sentença SQL são concatenados separados por espaço.
O eventual ponto e vírgula final será removido.
Todas as sentenças SQL, exceto a última, serão executadas diretamente.
Para tabela-IN, a última sentença SQL pode ser um comando SELECT que se inicia
com \verb|'SELECT '| em letras maiúsculas. Se a cadeia não se inicia com
\verb|'SELECT '|, se considera que é um nome de uma tabela e uma sentença
SELECT é automaticamente gerada.
Para tabela-OUT, a última sentença SQL pode conter um ou múltiplos pontos de
interrogação. Se contém um ponto de interrogação, é considerado um gabarito
para a rotina de escrita. Caso contrário, a cadeia é considerada um
nome de tabela e um gabarito INSERT é automaticamente gerado.
A rotina de escrita usa um gabarito com o pontos de interrogação e
o substitui o primeiro ponto de interrogação pelo primeiro parâmetro
de saída, o segundo ponto de interrogação, pelo segundo parâmetro e
assim por diante. Em seguida, o comando SQL é emitido.
O que segue é um exemplo da sentença table de saída:
\begin{verbatim}
table ta { l in LOCAIS } OUT
'ODBC'
'DSN=glpkdb;UID=glpkuser;PWD=glpkpassword'
'DROP TABLE IF EXISTS resultado;'
'CREATE TABLE resultado ( ID INT, LOC VARCHAR(255), QUAN DOUBLE );'
'INSERT INTO resultado 'VALUES ( 4, ?, ? )' :
l ~ LOC, quantidade[l] ~ QUAN;
\end{verbatim}
% \newpage
\noindent
Alternativamente pode se escrever como segue:
\begin{verbatim}
table ta { l in LOCAIS } OUT
'ODBC'
'DSN=glpkdb;UID=glpkuser;PWD=glpkpassword'
'DROP TABLE IF EXISTS resultado;'
'CREATE TABLE resultado ( ID INT, LOC VARCHAR(255), QUAN DOUBLE );'
'resultado' :
l ~ LOC, quantidade[l] ~ QUAN, 4 ~ ID;
\end{verbatim}
O uso de gabaritos com `\verb|?|' não só permite INSERT, como também o
UPDATE, DELETE, etc. Por exemplo:
\begin{verbatim}
table ta { l in LOCAIS } OUT
'ODBC'
'DSN=glpkdb;UID=glpkuser;PWD=glpkpassword'
'UPDATE resultado SET DATA = ' & data & ' WHERE ID = 4;'
'UPDATE resultado SET QUAN = ? WHERE LOC = ? AND ID = 4' :
quantidade[l], l;
\end{verbatim}
% The ODBC table driver allows connecting to SQL databases using an
% implementation of the ODBC interface based on the Call Level Interface
% (CLI).\footnote{The corresponding software standard is defined in
% ISO/IEC 9075-3:2003.}
%
% \para{Debian GNU/Linux.}
% Under Debian GNU/Linux the ODBC table driver uses the iODBC
% package,\footnote{See {\tt<http://www.iodbc.org/>}.} which should be
% installed before building the GLPK package. The installation can be
% effected with the following command:
%
% \begin{verbatim}
% sudo apt-get install libiodbc2-dev
% \end{verbatim}
%
% Note that on configuring the GLPK package to enable using the iODBC
% library the option `\verb|--enable-odbc|' should be passed to the
% configure script.
%
% The individual databases should be entered for systemwide usage in
% \verb|/etc/odbc.ini| and\linebreak \verb|/etc/odbcinst.ini|. Database
% connections to be used by a single user are specified by files in the
% home directory (\verb|.odbc.ini| and \verb|.odbcinst.ini|).
%
% \para{Microsoft Windows.}
% Under Microsoft Windows the ODBC table driver uses the Microsoft ODBC
% library. To enable this feature the symbol:
%
% \begin{verbatim}
% #define ODBC_DLNAME "odbc32.dll"
% \end{verbatim}
%
% \noindent
% should be defined in the GLPK configuration file `\verb|config.h|'.
%
% Data sources can be created via the Administrative Tools from the
% Control Panel.
%
% To choose the ODBC table driver its name in the table statement should
% be specified as \verb|'ODBC'| or \verb|'iODBC'|.
%
% \newpage
%
% The argument list is specified as follows.
%
% The first argument is the connection string passed to the ODBC library,
% for example:
%
% \verb|'DSN=glpk;UID=user;PWD=password'|, or
%
% \verb|'DRIVER=MySQL;DATABASE=glpkdb;UID=user;PWD=password'|.
%
% Different parts of the string are separated by semicolons. Each part
% consists of a pair {\it fieldname} and {\it value} separated by the
% equal sign. Allowable fieldnames depend on the ODBC library. Typically
% the following fieldnames are allowed:
%
% \verb|DATABASE | database;
%
% \verb|DRIVER | ODBC driver;
%
% \verb|DSN | name of a data source;
%
% \verb|FILEDSN | name of a file data source;
%
% \verb|PWD | user password;
%
% \verb|SERVER | database;
%
% \verb|UID | user name.
%
% The second argument and all following are considered to be SQL
% statements
%
% SQL statements may be spread over multiple arguments. If the last
% character of an argument is a semicolon this indicates the end of
% a SQL statement.
%
% The arguments of a SQL statement are concatenated separated by space.
% The eventual trailing semicolon will be removed.
%
% All but the last SQL statement will be executed directly.
%
% For IN-table the last SQL statement can be a SELECT command starting
% with the capitalized letters \verb|'SELECT '|. If the string does not
% start with \verb|'SELECT '| it is considered to be a table name and a
% SELECT statement is automatically generated.
%
% For OUT-table the last SQL statement can contain one or multiple
% question marks. If it contains a question mark it is considered a
% template for the write routine. Otherwise the string is considered a
% table name and an INSERT template is automatically generated.
%
% The writing routine uses the template with the question marks and
% replaces the first question mark by the first output parameter, the
% second question mark by the second output parameter and so forth. Then
% the SQL command is issued.
%
% The following is an example of the output table statement:
%
% \begin{verbatim}
% table ta { l in LOCATIONS } OUT
% 'ODBC'
% 'DSN=glpkdb;UID=glpkuser;PWD=glpkpassword'
% 'DROP TABLE IF EXISTS result;'
% 'CREATE TABLE result ( ID INT, LOC VARCHAR(255), QUAN DOUBLE );'
% 'INSERT INTO result 'VALUES ( 4, ?, ? )' :
% l ~ LOC, quantity[l] ~ QUAN;
% \end{verbatim}
%
% \newpage
%
% \noindent
% Alternatively it could be written as follows:
%
% \begin{verbatim}
% table ta { l in LOCATIONS } OUT
% 'ODBC'
% 'DSN=glpkdb;UID=glpkuser;PWD=glpkpassword'
% 'DROP TABLE IF EXISTS result;'
% 'CREATE TABLE result ( ID INT, LOC VARCHAR(255), QUAN DOUBLE );'
% 'result' :
% l ~ LOC, quantity[l] ~ QUAN, 4 ~ ID;
% \end{verbatim}
%
% Using templates with `\verb|?|' supports not only INSERT, but also
% UPDATE, DELETE, etc. For example:
%
% \begin{verbatim}
% table ta { l in LOCATIONS } OUT
% 'ODBC'
% 'DSN=glpkdb;UID=glpkuser;PWD=glpkpassword'
% 'UPDATE result SET DATE = ' & date & ' WHERE ID = 4;'
% 'UPDATE result SET QUAN = ? WHERE LOC = ? AND ID = 4' :
% quantity[l], l;
% \end{verbatim}
\section{Controlador de tabelas MySQL}
O controlador de tabelas MySQL permite a conexão a base de dados MySQL.
\para{Debian GNU/Linux.}
No Debian GNU/Linux o controlador de tabelas MySQL usa o pacote MySQL,
\footnote{Para fazer o download de arquivos de desenvolvimento, ver
{\tt<http://dev.mysql.com/downloads/mysql/>}.} que deve ser instalado
antes da criação do pacote GLPK. A instalação pode ser efetuada com
o seguinte comando:
\begin{verbatim}
sudo apt-get install libmysqlclient15-dev
\end{verbatim}
Note que ao configurar o pacote GLPK para habilitar o uso da biblioteca MySQL
a opção `\verb|--enable-mysql|' deve ser passada ao script de
configuração.
\para{Microsoft Windows.}
No Microsoft Windows o controlador de tabelas MySQL também usa
a biblioteca MySQL. Para habilitar esta funcionalidade o símbolo:
\begin{verbatim}
#define MYSQL_DLNAME "libmysql.dll"
\end{verbatim}
\noindent
deve ser definido no arquivo de configuração do GLPK `\verb|config.h|'.
Para escolher o controlador de tabelas MySQL, seu nome na sentença table deve
ser especificada como \verb|'MySQL'|.
A lista de argumentos é especificada como segue.
O primeiro argumento especifica como conectar a base de dados no estilo DSN,
por exemplo:
\verb|'Database=glpk;UID=glpk;PWD=gnu'|.
Diferentes partes da cadeia são separadas por ponto e vírgula. Cada parte
consiste de um par {\it nome-do-campo} e {\it valor} separado pelo sinal
de igualdade. Os seguintes nomes de campo são permitidos:
% \newpage
\verb|Server | servidor rodando a base de dados (localhost por padrão);
\verb|Database | nome da base de dados;
\verb|UID | nome de usuário;
\verb|PWD | senha de usuário;
\verb|Port | porta usada pelo servidor (3306 por padrão).
O segundo argumento e todos os seguintes são considerados sentenças SQL.
Sentenças SQL podem se estender sobre múltiplos argumentos. Se o último
caractere de um argumento é um ponto e vírgula, isto indica o fim de uma
sentença SQL.
Os argumentos de uma sentença SQL são concatenados e separados por espaço.
O eventual ponto e vírgula final será removido.
Todas sentenças SQL, menos a última, serão executadas diretamente.
Para tabela-IN, a última sentença SQL pode ser um comando SELECT iniciado
com letras maiúsculas \verb|'SELECT '|. Se a cadeia não inicia com
\verb|'SELECT '| é considerado um nome de tabela e a sentença
SELECT é automaticamente gerada.
Para tabela-OUT, a última sentença SQL pode conter um ou múltiplos pontos de
interrogação. Se contém um ponto de interrogação, é considerado um gabarito
para a rotina de escrita. Caso contrário, a cadeia é considerada um
nome de tabela e um gabarito INSERT é automaticamente gerado.
A rotina de escrita usa um gabarito com o pontos de interrogação e
o substitui o primeiro ponto de interrogação pelo primeiro parâmetro
de saída, o segundo ponto de interrogação, pelo segundo parâmetro e
assim por diante. Em seguida, o comando SQL é emitido.
O que segue é um exemplo da sentença table de saída:
\begin{verbatim}
table ta { l in LOCAIS } OUT
'MySQL'
'Database=glpkdb;UID=glpkuser;PWD=glpkpassword'
'DROP TABLE IF EXISTS resultado;'
'CREATE TABLE resultado ( ID INT, LOC VARCHAR(255), QUAN DOUBLE );'
'INSERT INTO resultado VALUES ( 4, ?, ? )' :
l ~ LOC, quantidade[l] ~ QUAN;
\end{verbatim}
\noindent
Alternativamente poderia ser escrito como segue:
\begin{verbatim}
table ta { l in LOCAIS } OUT
'MySQL'
'Database=glpkdb;UID=glpkuser;PWD=glpkpassword'
'DROP TABLE IF EXISTS resultado;'
'CREATE TABLE resultado ( ID INT, LOC VARCHAR(255), QUAN DOUBLE );'
'resultado' :
l ~ LOC, quantidade[l] ~ QUAN, 4 ~ ID;
\end{verbatim}
% \newpage
O uso de gabaritos com `\verb|?|' não só permite INSERT, como também o
UPDATE, DELETE, etc. Por exemplo:
\begin{verbatim}
table ta { l in LOCAIS } OUT
'MySQL'
'Database=glpkdb;UID=glpkuser;PWD=glpkpassword'
'UPDATE resultado SET DATE = ' & date & ' WHERE ID = 4;'
'UPDATE resultado SET QUAN = ? WHERE LOC = ? AND ID = 4' :
quantidade[l], l;
\end{verbatim}
% The MySQL table driver allows connecting to MySQL databases.
%
% \para{Debian GNU/Linux.}
% Under Debian GNU/Linux the MySQL table driver uses the MySQL
% package,\footnote{For download development files see
% {\tt<http://dev.mysql.com/downloads/mysql/>}.} which should be
% installed before building the GLPK package. The installation can be
% effected with the following command:
%
% \begin{verbatim}
% sudo apt-get install libmysqlclient15-dev
% \end{verbatim}
%
% Note that on configuring the GLPK package to enable using the MySQL
% library the option `\verb|--enable-mysql|' should be passed to the
% configure script.
%
% \para{Microsoft Windows.}
% Under Microsoft Windows the MySQL table driver also uses the MySQL
% library. To enable this feature the symbol:
%
% \begin{verbatim}
% #define MYSQL_DLNAME "libmysql.dll"
% \end{verbatim}
%
% \noindent
% should be defined in the GLPK configuration file `\verb|config.h|'.
%
% To choose the MySQL table driver its name in the table statement should
% be specified as \verb|'MySQL'|.
%
% The argument list is specified as follows.
%
% The first argument specifies how to connect the data base in the DSN
% style, for example:
%
% \verb|'Database=glpk;UID=glpk;PWD=gnu'|.
%
% Different parts of the string are separated by semicolons. Each part
% consists of a pair {\it fieldname} and {\it value} separated by the
% equal sign. The following fieldnames are allowed:
%
% \newpage
%
% \verb|Server | server running the database (defaulting to localhost);
%
% \verb|Database | name of the database;
%
% \verb|UID | user name;
%
% \verb|PWD | user password;
%
% \verb|Port | port used by the server (defaulting to 3306).
%
% The second argument and all following are considered to be SQL
% statements.
%
% SQL statements may be spread over multiple arguments. If the last
% character of an argument is a semicolon this indicates the end of
% a SQL statement.
%
% The arguments of a SQL statement are concatenated separated by space.
% The eventual trailing semicolon will be removed.
%
% All but the last SQL statement will be executed directly.
%
% For IN-table the last SQL statement can be a SELECT command starting
% with the capitalized letters \verb|'SELECT '|. If the string does not
% start with \verb|'SELECT '| it is considered to be a table name and a
% SELECT statement is automatically generated.
%
% For OUT-table the last SQL statement can contain one or multiple
% question marks. If it contains a question mark it is considered a
% template for the write routine. Otherwise the string is considered a
% table name and an INSERT template is automatically generated.
%
% The writing routine uses the template with the question marks and
% replaces the first question mark by the first output parameter, the
% second question mark by the second output parameter and so forth. Then
% the SQL command is issued.
%
% The following is an example of the output table statement:
%
% \begin{verbatim}
% table ta { l in LOCATIONS } OUT
% 'MySQL'
% 'Database=glpkdb;UID=glpkuser;PWD=glpkpassword'
% 'DROP TABLE IF EXISTS result;'
% 'CREATE TABLE result ( ID INT, LOC VARCHAR(255), QUAN DOUBLE );'
% 'INSERT INTO result VALUES ( 4, ?, ? )' :
% l ~ LOC, quantity[l] ~ QUAN;
% \end{verbatim}
%
% \noindent
% Alternatively it could be written as follows:
%
% \begin{verbatim}
% table ta { l in LOCATIONS } OUT
% 'MySQL'
% 'Database=glpkdb;UID=glpkuser;PWD=glpkpassword'
% 'DROP TABLE IF EXISTS result;'
% 'CREATE TABLE result ( ID INT, LOC VARCHAR(255), QUAN DOUBLE );'
% 'result' :
% l ~ LOC, quantity[l] ~ QUAN, 4 ~ ID;
% \end{verbatim}
%
% \newpage
%
% Using templates with `\verb|?|' supports not only INSERT, but also
% UPDATE, DELETE, etc. For example:
%
% \begin{verbatim}
% table ta { l in LOCATIONS } OUT
% 'MySQL'
% 'Database=glpkdb;UID=glpkuser;PWD=glpkpassword'
% 'UPDATE result SET DATE = ' & date & ' WHERE ID = 4;'
% 'UPDATE result SET QUAN = ? WHERE LOC = ? AND ID = 4' :
% quantity[l], l;
% \end{verbatim}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% ##################### PAREI AQUI % #####################
\chapter{Resolvendo modelos com glpsol}
O pacote GLPK \footnote{{\tt http://www.gnu.org/software/glpk/}}
inclui o programa {\tt glpsol}, um solver de PL/PIM autônomo. Este
programa pode ser chamado por uma linha de comando ou pelo shell para
resolver modelos escritos na \linebreak linguagem de modelagem GNU MathProg.
Para comunicar ao solver que o arquivo de entrada contém uma descrição
do modelo, é necessário especificar a opção \verb|--model| na linha de
comando. Por exemplo:
\begin{verbatim}
glpsol --model foo.mod
\end{verbatim}
Às vezes é necessário usar a seção de dados posicionado em um arquivo
separado. Neste caso, deve-se usar o seguinte comando:
\begin{verbatim}
glpsol --model foo.mod --data foo.dat
\end{verbatim}
\noindent Note que ser o arquivo de modelo também contém a seção de dados,
aquela seção é ignorada.
Também é permitido especificar mais de um arquivo contendo a seção de dados,
por exemplo:
\begin{verbatim}
glpsol --model foo.mod --data foo1.dat --data foo2.dat
\end{verbatim}
Se a descrição do modelo contém alguma sentença display e/ou printf,
o resultado é enviado para o terminal por padrão. Se há a necessidade
de redirecionar a saída para um arquivo, deve-se usar o seguinte comando:
\begin{verbatim}
glpsol --model foo.mod --display foo.out
\end{verbatim}
Se há a necessidade de ver o problema que está sendo gerado pelo tradutor
de modelo, deve-ser usar a opção \verb|--wlp| como segue:
\begin{verbatim}
glpsol --model foo.mod --wlp foo.lp
\end{verbatim}
\noindent Neste caso, os dados do problema são escritos no arquivo
\verb|foo.lp| no formato CPLEX LP viável para análise visual.
Ás vezes, é necessário checar a descrição do modelo sem ter que resolver
a instância do problema gerado. Neste caso, deve-se especificar a opção
\verb|--check|, por exemplo:
\begin{verbatim}
glpsol --check --model foo.mod --wlp foo.lp
\end{verbatim}
\newpage
Se há a necessidade de escrever uma solução numérica obtida pelo solver
para um arquivo, deve-se usar o seguinte comando:
\begin{verbatim}
glpsol --model foo.mod --output foo.sol
\end{verbatim}
\noindent neste caso, a solução é escrita no arquivo \verb|foo.sol|
em formato de texto plano, viável para análise visual.
A lista completa de opções do \verb|glpsol| pode ser encontrada no manual
de referência do GLPK incluída na distribuição do GLPK.
% The GLPK package\footnote{{\tt http://www.gnu.org/software/glpk/}}
% includes the program {\tt glpsol}, a stand-alone LP/MIP solver. This
% program can be launched from the command line or from the shell to
% solve models written in the GNU MathProg modeling language.
%
% To tell the solver that the input file contains a model description you
% need to specify the option \verb|--model| in the command line.
% For example:
%
% \begin{verbatim}
% glpsol --model foo.mod
% \end{verbatim}
%
% Sometimes it is necessary to use the data section placed in a separate
% file, in which case you may use the following command:
%
% \begin{verbatim}
% glpsol --model foo.mod --data foo.dat
% \end{verbatim}
%
% \noindent Note that if the model file also contains the data section,
% that section is ignored.
%
% It is also allowed to specify more than one file containing the data
% section, for example:
%
% \begin{verbatim}
% glpsol --model foo.mod --data foo1.dat --data foo2.dat
% \end{verbatim}
%
% If the model description contains some display and/or printf
% statements, by default the output is sent to the terminal. If you need
% to redirect the output to a file, you may use the following command:
%
% \begin{verbatim}
% glpsol --model foo.mod --display foo.out
% \end{verbatim}
%
% If you need to look at the problem, which has been generated by the
% model translator, you may use the option \verb|--wlp| as follows:
%
% \begin{verbatim}
% glpsol --model foo.mod --wlp foo.lp
% \end{verbatim}
%
% \noindent In this case the problem data is written to file
% \verb|foo.lp| in CPLEX LP format suitable for visual analysis.
%
% Sometimes it is needed merely to check the model description not
% solving the generated problem instance. In this case you may specify
% the option \verb|--check|, for example:
%
% \begin{verbatim}
% glpsol --check --model foo.mod --wlp foo.lp
% \end{verbatim}
%
% \newpage
%
% If you need to write a numeric solution obtained by the solver to
% a file, you may use the following command:
%
% \begin{verbatim}
% glpsol --model foo.mod --output foo.sol
% \end{verbatim}
%
% \noindent in which case the solution is written to file \verb|foo.sol|
% in a plain text format suitable for visual analysis.
%
% The complete list of the \verb|glpsol| options can be found in the
% GLPK reference manual included in the GLPK distribution.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\chapter{Exemplo de descrição de modelo}
\section{Descrição de modelo escrito em MathProg}
Este é um exemplo completo de descrição de modelo escrito na linguagem
de modelagem GNU MathProg.
\bigskip
\begin{verbatim}
# UM PROBLEMA DE TRANSPORTE
#
# Este problema encontra a logística de custo mínimo que atende das demandas
# de mercado e as ofertas das fábricas.
#
# Referência:
# Dantzig G B, "Linear Programming and Extensions."
# Princeton University Press, Princeton, New Jersey, 1963,
# Chapter 3-3.
set I;
/* fábricas de enlatados*/
set J;
/* mercados */
param a{i in I};
/* capacidade da fábrica i, em caixas */
param b{j in J};
/* demanda no mercado j, em caixas */
param d{i in I, j in J};
/* distância, em milhares de milhas */
param f;
/* frete, em dólares por caixa a cada mil milhas */
param c{i in I, j in J} := f * d[i,j] / 1000;
/* custo de transporte, em milhares de dólares por caixa */
var x{i in I, j in J} >= 0;
/* quantidade enviada, em caixas */
minimize custo: sum{i in I, j in J} c[i,j] * x[i,j];
/* custo total de transporte, em milhares de dólares */
s.t. suprimento{i in I}: sum{j in J} x[i,j] <= a[i];
/* observa o limite de suprimento na fábrica i */
s.t. demanda{j in J}: sum{i in I} x[i,j] >= b[j];
/* satisfaz a demanda do mercado j */
data;
set I := Seattle San-Diego;
set J := New-York Chicago Topeka;
param a := Seattle 350
San-Diego 600;
param b := New-York 325
Chicago 300
Topeka 275;
param d : New-York Chicago Topeka :=
Seattle 2.5 1.7 1.8
San-Diego 2.5 1.8 1.4 ;
param f := 90;
end;
\end{verbatim}
% Below here is a complete example of the model description written in
% the GNU MathProg modeling language.
%
% \bigskip
%
% \begin{verbatim}
% # A TRANSPORTATION PROBLEM
% #
% # This problem finds a least cost shipping schedule that meets
% # requirements at markets and supplies at factories.
% #
% # References:
% # Dantzig G B, "Linear Programming and Extensions."
% # Princeton University Press, Princeton, New Jersey, 1963,
% # Chapter 3-3.
%
% set I;
% /* canning plants */
%
% set J;
% /* markets */
%
% param a{i in I};
% /* capacity of plant i in cases */
%
% param b{j in J};
% /* demand at market j in cases */
%
% param d{i in I, j in J};
% /* distance in thousands of miles */
%
% param f;
% /* freight in dollars per case per thousand miles */
%
% param c{i in I, j in J} := f * d[i,j] / 1000;
% /* transport cost in thousands of dollars per case */
%
% var x{i in I, j in J} >= 0;
% /* shipment quantities in cases */
%
% minimize cost: sum{i in I, j in J} c[i,j] * x[i,j];
% /* total transportation costs in thousands of dollars */
%
% s.t. supply{i in I}: sum{j in J} x[i,j] <= a[i];
% /* observe supply limit at plant i */
%
% s.t. demand{j in J}: sum{i in I} x[i,j] >= b[j];
% /* satisfy demand at market j */
%
% data;
%
% set I := Seattle San-Diego;
%
% set J := New-York Chicago Topeka;
%
% param a := Seattle 350
% San-Diego 600;
%
% param b := New-York 325
% Chicago 300
% Topeka 275;
%
% param d : New-York Chicago Topeka :=
% Seattle 2.5 1.7 1.8
% San-Diego 2.5 1.8 1.4 ;
%
% param f := 90;
%
% end;
% \end{verbatim}
\newpage
\section{Instância gerada do problema de PL}
Este é o resultado da tradução do modelo de exemplo produzido
pelo solver \verb|glpsol| e escrito no formato CPLEX LP
com a opção \verb|--wlp|.
\medskip
\begin{verbatim}
\* Problem: transporte *\
Minimize
custo: + 0.225 x(Seattle,New~York) + 0.153 x(Seattle,Chicago)
+ 0.162 x(Seattle,Topeka) + 0.225 x(San~Diego,New~York)
+ 0.162 x(San~Diego,Chicago) + 0.126 x(San~Diego,Topeka)
Subject To
suprimento(Seattle): + x(Seattle,New~York) + x(Seattle,Chicago)
+ x(Seattle,Topeka) <= 350
suprimento(San~Diego): + x(San~Diego,New~York) + x(San~Diego,Chicago)
+ x(San~Diego,Topeka) <= 600
demanda(New~York): + x(Seattle,New~York) + x(San~Diego,New~York) >= 325
demanda(Chicago): + x(Seattle,Chicago) + x(San~Diego,Chicago) >= 300
demanda(Topeka): + x(Seattle,Topeka) + x(San~Diego,Topeka) >= 275
End
\end{verbatim}
\section{solução ótima do problema de PL}
Esta é a solução ótima da instância gerada do problema de PL
encontrada pelo solver \verb|glpsol| e escrita em formato de texto plano
com a opção\verb|--output|.
\medskip
\begin{footnotesize}
\begin{verbatim}
Problem: transporte
Rows: 6
Columns: 6
Non-zeros: 18
Status: OPTIMAL
Objective: custo = 153.675 (MINimum)
No. Row name St Activity Lower bound Upper bound Marginal
------ ------------ -- ------------- ------------- ------------- -------------
1 cust B 153.675
2 suprimento[Seattle]
NU 350 350 < eps
3 suprimento[San-Diego]
B 550 600
4 demanda[New-York]
NL 325 325 0.225
5 demanda[Chicago]
NL 300 300 0.153
6 demanda[Topeka]
NL 275 275 0.126
No. Column name St Activity Lower bound Upper bound Marginal
------ ------------ -- ------------- ------------- ------------- -------------
1 x[Seattle,New-York]
B 50 0
2 x[Seattle,Chicago]
B 300 0
3 x[Seattle,Topeka]
NL 0 0 0.036
4 x[San-Diego,New-York]
B 275 0
5 x[San-Diego,Chicago]
NL 0 0 0.009
6 x[San-Diego,Topeka]
B 275 0
End of output
\end{verbatim}
\end{footnotesize}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\newpage
\section*{Agradecimentos}
\addcontentsline{toc}{chapter}{Agradecimentos}
Os autores gostariam de agradecer as seguintes pessoas que gentilmente leram,
comentaram e corrigiram o rascunho deste documento:
\noindent Juan Carlos Borras \verb|<borras@cs.helsinki.fi>|
\noindent Harley Mackenzie \verb|<hjm@bigpond.com>|
\noindent Robbie Morrison \verb|<robbie@actrix.co.nz>|
\end{document}
|