MQ for Sage toric varieties / trac_xxxx_palp_database.patch

The default branch has multiple heads

   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
# HG changeset patch
# Parent b9fec0145f03c4b3f9c9bf5f650f9d8c1604ca19

diff --git a/sage/geometry/integral_points.pyx b/sage/geometry/integral_points.pyx
--- a/sage/geometry/integral_points.pyx
+++ b/sage/geometry/integral_points.pyx
@@ -333,7 +333,8 @@
 # rectangular bounding box) it is faster to naively enumerate the
 # points. This saves the overhead of triangulating the polytope etc.
 
-def rectangular_box_points(box_min, box_max, polyhedron=None):
+def rectangular_box_points(box_min, box_max, polyhedron=None, 
+                           count_only=False, return_saturated=False):
     r"""
     Return the integral points in the lattice bounding box that are
     also contained in the given polyhedron.
@@ -350,16 +351,35 @@
       :class:`~sage.geometry.polyhedron.base.Polyhedron_base`, a PPL
       :class:`~sage.libs.ppl.C_Polyhedron`, or ``None`` (default).
 
+    - ``count_only`` -- Boolean (default: ``False``). Whether to
+      return only the total number of vertices, and not their
+      coordinates. Enabling this option speeds up the
+      enumeration. Cannot be combined with the ``return_saturated``
+      option.
+
+    - ``return_saturated`` -- Boolean (default: ``False``. Whether to
+      also return which inequalities are saturated for each point of
+      the polyhedron. Enabling this slows down the enumeration. Cannot
+      be combined with the ``count_only`` option.
+
     OUTPUT:
 
-    A tuple containing the integral points of the rectangular box
-    spanned by `box_min` and `box_max` and that lie inside the
-    ``polyhedron``. For sufficiently large bounding boxes, this are
-    all integral points of the polyhedron. 
+    By default, this function returns a tuple containing the integral
+    points of the rectangular box spanned by `box_min` and `box_max`
+    and that lie inside the ``polyhedron``. For sufficiently large
+    bounding boxes, this are all integral points of the polyhedron.
 
     If no polyhedron is specified, all integral points of the
     rectangular box are returned.
 
+    If ``count_only`` is specified, only the total number (an integer)
+    of found lattice points is returned.
+
+    If ``return_saturated`` is enabled, then for each integral point a
+    pair ``(point, Hrep)`` is returned where ``point`` is the point
+    and ``Hrep`` is the set of indices of the H-representation objects
+    that are saturated at the point.
+
     ALGORITHM:
 
     This function implements the naive algorithm towards counting
@@ -404,6 +424,10 @@
          (1, 1, 0), (1, 1, 1), (1, 1, 2), (1, 1, 3), 
          (1, 2, 0), (1, 2, 1), (1, 2, 2), (1, 2, 3))
 
+        sage: from sage.geometry.integral_points import rectangular_box_points
+        sage: rectangular_box_points([0,0,0],[1,2,3], count_only=True)
+        24
+
         sage: cell24 = polytopes.twenty_four_cell()
         sage: rectangular_box_points([-1]*4, [1]*4, cell24)
         ((-1, 0, 0, 0), (0, -1, 0, 0), (0, 0, -1, 0), (0, 0, 0, -1), 
@@ -419,6 +443,9 @@
         sage: len( rectangular_box_points([-d]*4, [d]*4, dilated_cell24) )
         3625
 
+        sage: rectangular_box_points([-d]*4, [d]*4, dilated_cell24, count_only=True)
+        3625
+
         sage: polytope = Polyhedron([(-4,-3,-2,-1),(3,1,1,1),(1,2,1,1),(1,1,3,0),(1,3,2,4)])
         sage: pts = rectangular_box_points([-4]*4, [4]*4, polytope); pts
         ((-4, -3, -2, -1), (-1, 0, 0, 1), (0, 1, 1, 1), (1, 1, 1, 1), (1, 1, 3, 0), 
@@ -446,7 +473,7 @@
         201
 
     Using a PPL polyhedron::
-    
+
         sage: from sage.libs.ppl import Variable, Generator_System, C_Polyhedron, point
         sage: gs = Generator_System()
         sage: x = Variable(0); y = Variable(1); z = Variable(2)
@@ -458,8 +485,28 @@
         sage: rectangular_box_points([0]*3, [3]*3, poly)
         ((0, 1, 0), (0, 1, 1), (0, 1, 2), (0, 1, 3), (1, 1, 0), (1, 1, 1), (1, 1, 2), (1, 1, 3), 
          (2, 1, 0), (2, 1, 1), (2, 1, 2), (2, 1, 3), (3, 1, 0), (3, 1, 1), (3, 1, 2), (3, 1, 3))
+
+    Optionally, return the information about the saturated inequalities as well::
+
+        sage: cube = polytopes.n_cube(3)
+        sage: cube.Hrepresentation(0)              
+        An inequality (0, 0, -1) x + 1 >= 0
+        sage: cube.Hrepresentation(1)
+        An inequality (0, -1, 0) x + 1 >= 0
+        sage: cube.Hrepresentation(2)
+        An inequality (-1, 0, 0) x + 1 >= 0
+        sage: rectangular_box_points([0]*3, [1]*3, cube, return_saturated=True)
+        (((0, 0, 0), frozenset([])), 
+         ((0, 0, 1), frozenset([0])), 
+         ((0, 1, 0), frozenset([1])), 
+         ((0, 1, 1), frozenset([0, 1])), 
+         ((1, 0, 0), frozenset([2])), 
+         ((1, 0, 1), frozenset([0, 2])), 
+         ((1, 1, 0), frozenset([1, 2])), 
+         ((1, 1, 1), frozenset([0, 1, 2])))
     """
     assert len(box_min)==len(box_max)
+    assert not (count_only and return_saturated)
     cdef int d = len(box_min)
     diameter = sorted([ (box_max[i]-box_min[i], i) for i in range(0,d) ], reverse=True)
     diameter_value = [ x[0] for x in diameter ]
@@ -472,13 +519,28 @@
     box_max = sort_perm.action(box_max)
     inequalities = InequalityCollection(polyhedron, sort_perm, box_min, box_max)
 
+    if count_only: 
+        return loop_over_rectangular_box_points(box_min, box_max, inequalities, d, count_only)
+
+    points = []
     v = vector(ZZ, d)
-    points = []
-    for p in loop_over_rectangular_box_points(box_min, box_max, inequalities, d):
-        #  v = vector(ZZ, orig_perm.action(p))   # too slow
-        for i in range(0,d):
-            v[i] = p[orig_perm_list[i]]
-        points.append(copy.copy(v))
+    if not return_saturated:
+        for p in loop_over_rectangular_box_points(box_min, box_max, inequalities, d, count_only):
+            #  v = vector(ZZ, orig_perm.action(p))   # too slow
+            for i in range(0,d):
+                v.set(i, p[orig_perm_list[i]])
+            v_copy = copy.copy(v)
+            v_copy.set_immutable()
+            points.append(v_copy)
+    else:
+        for p, saturated in \
+                loop_over_rectangular_box_points_saturated(box_min, box_max, inequalities, d):
+            for i in range(0,d):
+                v.set(i, p[orig_perm_list[i]])
+            v_copy = copy.copy(v)
+            v_copy.set_immutable()
+            points.append( (v_copy, saturated) )
+
     return tuple(points)
 
 
@@ -501,7 +563,7 @@
     return result
 
 
-cdef loop_over_rectangular_box_points(box_min, box_max, inequalities, int d):
+cdef loop_over_rectangular_box_points(box_min, box_max, inequalities, int d, bint count_only):
     """
     The inner loop of :func:`rectangular_box_points`.
     
@@ -514,12 +576,78 @@
 
     - ``d`` -- the ambient space dimension.
 
+    - ``count_only`` -- whether to only return the total number of
+      lattice points.
+
     OUTPUT:
 
     The integral points in the bounding box satisfying all
     inequalities.
     """
     cdef int inc
+    if count_only:
+        points = 0
+    else:
+        points = []
+    p = copy.copy(box_min)
+    inequalities.prepare_next_to_inner_loop(p)
+    while True:
+        inequalities.prepare_inner_loop(p)
+        i_min = box_min[0]
+        i_max = box_max[0]
+        # Find the lower bound for the allowed region
+        while i_min <= i_max:
+            if inequalities.are_satisfied(i_min):
+                break
+            i_min += 1
+        # Find the upper bound for the allowed region
+        while i_min <= i_max:
+            if inequalities.are_satisfied(i_max):
+                break
+            i_max -= 1
+        # The points i_min .. i_max are contained in the polyhedron
+        if count_only:
+            if i_max>=i_min:
+                points += i_max-i_min+1
+        else:
+            i = i_min
+            while i <= i_max:
+                p[0] = i
+                points.append(tuple(p))
+                i += 1
+        # finally increment the other entries in p to move on to next inner loop
+        inc = 1
+        if d==1: return points
+        while True:
+            if p[inc]==box_max[inc]:
+                p[inc] = box_min[inc]
+                inc += 1
+                if inc==d:
+                    return points
+            else:
+                p[inc] += 1
+                break
+        if inc>1:
+            inequalities.prepare_next_to_inner_loop(p)
+
+
+
+cdef loop_over_rectangular_box_points_saturated(box_min, box_max, inequalities, int d):
+    """
+    The analog of :func:`rectangular_box_points` except that it keeps
+    track of which inequalities are saturated.
+    
+    INPUT:
+
+    See :func:`rectangular_box_points`.
+
+    OUTPUT:
+
+    The integral points in the bounding box satisfying all
+    inequalities, each point being returned by a coordinate vector and
+    a set of H-representation object indices.
+    """
+    cdef int inc
     points = []
     p = copy.copy(box_min)
     inequalities.prepare_next_to_inner_loop(p)
@@ -541,7 +669,8 @@
         i = i_min
         while i <= i_max:
             p[0] = i
-            points.append(tuple(p))
+            saturated = inequalities.satisfied_as_equalities(i)
+            points.append( (tuple(p), saturated) )
             i += 1
         # finally increment the other entries in p to move on to next inner loop
         inc = 1
@@ -670,7 +799,7 @@
         return inner_loop_variable*self.coeff + self.cache == 0        
 
 
-
+# if dim>20 then we always use the generic inequalities (Inequality_generic)
 DEF INEQ_INT_MAX_DIM = 20
 
 cdef class Inequality_int:
@@ -1195,10 +1324,9 @@
 
         OUTPUT:
         
-        A tuple of integers in ascending order. Each integer is the
-        index of a H-representation object of the
-        polyhedron. Equalities are treated as a pair of opposite
-        inequalities.  
+        A set of integers in ascending order. Each integer is the
+        index of a H-representation object of the polyhedron (either a
+        inequality or an equation).
         
         EXAMPLES::
         
@@ -1208,11 +1336,11 @@
             sage: ieqs.prepare_next_to_inner_loop([-1,0])
             sage: ieqs.prepare_inner_loop([-1,0])
             sage: ieqs.satisfied_as_equalities(-1)
-            (1,)
+            frozenset([1])
             sage: ieqs.satisfied_as_equalities(0)
-            (0, 1)
+            frozenset([0, 1])
             sage: ieqs.satisfied_as_equalities(1)
-            (1,)
+            frozenset([1])
         """
         cdef int i
         result = []
@@ -1224,7 +1352,7 @@
             ineq = self.ineqs_generic[i]
             if (<Inequality_generic>ineq).is_equality(inner_loop_variable):
                 result.append( (<Inequality_generic>ineq).index )
-        return tuple(uniq(result))
+        return frozenset(result)
     
 
 
diff --git a/sage/geometry/polyhedron/palp_database.py b/sage/geometry/polyhedron/palp_database.py
new file mode 100644
--- /dev/null
+++ b/sage/geometry/polyhedron/palp_database.py
@@ -0,0 +1,273 @@
+"""
+Access the PALP database(s) of reflexive lattice polytopes
+"""
+
+from subprocess import Popen, PIPE
+
+from sage.structure.sage_object import SageObject
+from sage.matrix.all import matrix
+from sage.rings.all import Integer, ZZ
+
+from sage.geometry.polyhedron.ppl_lattice_polytope import LatticePolytope_PPL
+from sage.geometry.polyhedron.constructor import Polyhedron
+
+"""
+for lp in ReflexivePolytopes(2):
+    cone = Cone([(1,r[0],r[1]) for r in lp.vertices().columns()])
+    fan = Fan([cone])
+    X = ToricVariety(fan)
+    ideal = X.affine_algebraic_patch(cone).defining_ideal()
+    print ideal.hilbert_series(), '\t', lp.npoints()
+"""
+
+
+
+#########################################################################
+class PALPreader(SageObject):
+    """
+    Read PALP database of polytopes.
+
+    EXAMPLES::
+
+        sage: from sage.geometry.polyhedron.palp_database import PALPreader
+        sage: polygons = PALPreader(2, '/home/vbraun/Sage/ReflexivePolyhedra4d/Full2d/zzdb')
+        sage: [ (p.n_Vrepresentation(), 
+        ...      len(p.integral_points())) for p in polygons ]
+        [(3, 4), (3, 10), (3, 5), (3, 9), (3, 7), (4, 6), (4, 8), (4, 9), 
+         (4, 5), (4, 5), (4, 9), (4, 7), (5, 8), (5, 6), (5, 7), (6, 7)]
+    """
+    def __init__(self, dim, data_basename, output='Polyhedron'):
+        """
+        The Python constructor
+
+        INPUT:
+
+        - ``dim`` -- integer. The dimension of the poylhedra
+        
+        - ``data_basename`` -- string. The filename for the PALP database to read
+        
+        - ``output`` -- string. How to return the reflexive
+          polyhedra. Allowed values = ``'list'``, ``'Polyhedron'`` (default),
+          and ``'PPL'``.
+        """
+        self._dim = dim
+        self._data_basename = data_basename
+        from sage.geometry.polyhedron.parent import Polyhedra
+        self._polyhedron_parent = Polyhedra(ZZ, dim)
+        self._output = output.lower()
+        
+    def _palp_Popen(self):
+        return Popen(["class.x", "-b2a", "-di", self._data_basename], stdout=PIPE)
+
+    def _read_vertices(self, stdout, rows, cols):
+        m = [ [] for col in range(0,cols) ]
+        for row in range(0,rows):
+            for col,x in enumerate(stdout.readline().split()):
+                m[col].append(ZZ(x))
+        return m
+    
+    def _read_vertices_transposed(self, stdout, rows, cols):
+        m = []
+        for row in range(0,rows):
+            m.append( [ ZZ(x) for x in stdout.readline().split() ] )
+        return m
+    
+    def _iterate_list(self, start, stop, step):
+        if start is None:
+            start = 0
+        if step is None:
+            step = 1
+        palp = self._palp_Popen()
+        try:
+            palp_out = palp.stdout
+            i = 0
+            while True:
+                l = palp_out.readline().strip()
+                if l=='' or l.startswith('#'): 
+                    return  # EOF
+                l=l.split()
+                dim = ZZ(l[0]);  # dimension
+                n = ZZ(l[1]);    # number of vertices
+                if i>=start and (i-start) % step == 0:
+                    if dim == self._dim:
+                        vertices = self._read_vertices(palp_out, dim, n)
+                    elif n == self._dim:  # PALP sometimes returns transposed data #@!#@
+                        vertices = self._read_vertices_transposed(palp_out, dim, n)
+                    else:
+                        raise ValueError('PALP output dimension mismatch.')
+                    yield vertices
+                else: 
+                    for row in range(0,dim): 
+                        palp_out.readline()
+                i += 1
+                if stop is not None and i>=stop:
+                    return
+        finally:
+            palp.poll()
+            if palp.returncode is None:
+                palp.terminate()
+            palp.poll()
+            if palp.returncode is None:
+                palp.kill()
+    
+
+    def _iterate_Polyhedron(self, start, stop, step):
+        parent = self._polyhedron_parent
+        for vertices in self._iterate_list(start, stop, step):
+            p = parent.element_class(parent, [vertices,[],[]], None)
+            yield p
+            p.delete()
+
+    def _iterate_PPL(self, start, stop, step):
+        for vertices in self._iterate_list(start, stop, step):
+            yield LatticePolytope_PPL(*vertices)
+
+    def _iterate(self, output=None):
+        if output is None: 
+            output = self._output
+        if output == 'polyhedron':
+            return self._iterate_Polyhedron
+        elif output == 'ppl':
+            return self._iterate_PPL
+        elif output == 'list':
+            return self._iterate_list
+        else:
+            raise TypeError('Unknown output format (='+str(self._output)+').')
+
+    def __iter__(self):
+        """
+        Iterate over all polytopes.
+        """
+        iterator = self._iterate()
+        return iterator(None, None, None)
+
+    def __getitem__(self, item):
+        """
+        Return the polytopes(s) indexed by ``item``.
+
+        EXAMPLES::
+
+            sage: from sage.geometry.polyhedron.palp_database import PALPreader
+            sage: palp = PALPreader(4, '/home/vbraun/Sage/ReflexivePolyhedra4d/Full4d/zzdb')
+            sage: list(palp[1000:3000:1000])
+            [A 4-dimensional polyhedron in ZZ^4 defined as the convex hull of 5 vertices, 
+             A 4-dimensional polyhedron in ZZ^4 defined as the convex hull of 6 vertices]
+        """
+        iterator = self._iterate()
+        if isinstance(item, slice):
+            return iterator(item.start, item.stop, item.step)
+        else:
+            try:
+                return iterator(item, item+1, 1).next()
+            except StopIteration:
+                raise IndexError('Index out of range.')
+
+
+
+#########################################################################
+class Reflexive4dHodge(PALPreader):
+    """
+    Read the PALP database for hodge numbers of 4d polytopes.
+
+    EXAMPLES:
+
+        sage: from sage.geometry.polyhedron.palp_database import Reflexive4dHodge
+        sage: ref = Reflexive4dHodge(1,101)
+        sage: iter(ref).next().Vrepresentation()
+        (A vertex at (-1, -1, -1, -1), A vertex at (0, 0, 0, 1), 
+         A vertex at (0, 0, 1, 0), A vertex at (0, 1, 0, 0), A vertex at (1, 0, 0, 0))
+
+    from sage.geometry.polyhedron.palp_database import Reflexive4dHodge
+    ref = Reflexive4dHodge(30,31, output='PPL')
+    def f():
+        for p in ref[100:1100]:
+            pass
+
+    %prun f()
+
+    from sage.geometry.polyhedron.palp_database import Reflexive4dHodge
+    ref = Reflexive4dHodge(30,31)
+    def f():
+        for p in ref[100:200]:
+            for fiber in p.fibration_generator(2):
+                pass
+
+    %prun f()
+    """
+    def __init__(self, h11, h21, **kwds):
+        dim = 4
+        data_basename = '/home/vbraun/Sage/ReflexivePolyhedra4d/Hodge4d/all'
+        PALPreader.__init__(self, dim, data_basename, **kwds)
+        self._h11 = h11
+        self._h21 = h21
+        
+    def _palp_Popen(self):
+        return Popen(['/home/vbraun/Code/palp/class.x', '-He', 
+                      'H'+str(self._h21)+':'+str(self._h11)+'L100000000', 
+                      '-di', self._data_basename], stdout=PIPE)
+        
+
+
+
+
+#########################################################################
+class PALPfibrations2(SageObject):
+
+      
+    def __init__(self, filename):
+        self._filename=filename
+        self._file = open(filename)
+
+
+    def parse(self, line):
+        # 2 2 3 39 53 99 198=d M:6823 13 N:40 9 V:24,2,5870 [35400]
+        result={}
+        result['str']=line
+        data = line.split(' ')
+        weights = []
+        while not data[0].endswith('=d'):
+            weights.append( ZZ(data.pop(0)) )
+        result['weight']=weights
+        result['tdeg']=ZZ(data.pop(0)[0:-2])
+        result['Mpoints']  =ZZ(data.pop(0)[2:])
+        result['Mvertices']=ZZ(data.pop(0))
+        result['Npoints']  =ZZ(data.pop(0)[2:])
+        result['Nvertices']=ZZ(data.pop(0))
+        assert sum(result['weight'])==result['tdeg']
+        return result
+
+
+    def __iter__(self):
+        while True:
+            line = self._file.readline()
+            if line=='':
+                raise StopIteration
+            yield self.parse(line)
+
+
+    def fibrations(self,codimension):
+        for poly in self.__iter__():
+            weights = (" ").join(map(str,poly['weight'] + [poly['tdeg']] )) + "\n"
+            palp = Popen(["poly.x", "-f"+str(codimension)+str(codimension)],
+                         stdin=PIPE, stdout=PIPE, stderr=PIPE)
+            ans, err = palp.communicate(input=weights)
+
+            if err!="":
+                print err
+                raise ValueError
+
+            fibration_data=ans.splitlines()
+            while len(fibration_data)>0:
+                line=fibration_data.pop(0)
+                poly['fibration']=line
+                line=line.split()
+                d=ZZ(line[0])
+                n=ZZ(line[1])
+                poly['dimension']=d
+                poly['nvertices']=n
+                P=[]
+                for i in range(0,d):
+                    P.append(map(ZZ,fibration_data.pop(0).split()))
+                poly['matrix']=matrix(P)
+                yield poly
+
diff --git a/sage/geometry/polyhedron/ppl_lattice_polytope.py b/sage/geometry/polyhedron/ppl_lattice_polytope.py
new file mode 100644
--- /dev/null
+++ b/sage/geometry/polyhedron/ppl_lattice_polytope.py
@@ -0,0 +1,754 @@
+"""
+Fast Lattice Polytopes using PPL.
+
+The :func:`LatticePolytope_PPL` class is a thin wrapper around PPL
+polyhedra. Its main purpose is to be fast to construct, at the cost of
+being much less full-featured than the usual polyhedra.
+
+from sage.geometry.polyhedron.palp_database import Reflexive4dHodge
+ref = Reflexive4dHodge(12,22, output='PPL')
+
+def f():
+    fibrations = []
+    for p in ref[0:1000]:
+        for fiber in p.fibration_generator(2):
+            base = p.base(fiber)
+            if base.is_isomorphic('P2'):
+                #print fiber.vertices()
+                fibrations.append( (fiber,p,base) )
+    return fibrations
+
+from sage.geometry.polyhedron.palp_database import Reflexive4dHodge
+ref = Reflexive4dHodge(12,22, output='PPL')
+
+def f():
+    fibrations = 0
+    for p in ref:
+        for f in p.fibration_generator_2(2):
+            fibrations += 1
+    return fibrations
+
+f()
+
+%prun f()
+
+"""
+
+########################################################################
+#       Copyright (C) 2011 Volker Braun <vbraun.name@gmail.com>
+#
+#  Distributed under the terms of the GNU General Public License (GPL)
+#
+#                  http://www.gnu.org/licenses/
+########################################################################
+
+
+
+import copy
+from sage.rings.integer import GCD_list
+from sage.rings.integer_ring import ZZ
+from sage.misc.all import union, cached_method, prod, uniq
+from sage.matrix.constructor import matrix, column_matrix, vector, diagonal_matrix
+from sage.libs.ppl import (
+    C_Polyhedron, Linear_Expression, Variable,
+    point, ray, line, Generator, Generator_System, 
+    Constraint_System,
+    Poly_Con_Relation)
+
+
+
+
+########################################################################
+def LatticePolytope_PPL(*args):
+    """
+    Construct a new instance of the PPL-based lattice polytope class.
+
+    EXAMPLES::
+
+        sage: from sage.geometry.polyhedron.ppl_lattice_polytope import LatticePolytope_PPL
+        sage: LatticePolytope_PPL((0,0),(1,0),(0,1))
+        A 2-dimensional polyhedron in QQ^2 defined as the convex hull of 3 points
+
+        sage: from sage.libs.ppl import point, Generator_System, C_Polyhedron, Linear_Expression, Variable
+        sage: p = point(Linear_Expression([2,3],0));  p
+        point(2/1, 3/1)
+        sage: LatticePolytope_PPL(p)
+        A 0-dimensional polyhedron in QQ^2 defined as the convex hull of 1 point
+
+        sage: P = C_Polyhedron(Generator_System(p));  P
+        A 0-dimensional polyhedron in QQ^2 defined as the convex hull of 1 point
+        sage: LatticePolytope_PPL(P)
+        A 0-dimensional polyhedron in QQ^2 defined as the convex hull of 1 point
+
+    A ``TypeError`` is raised if the arguments do not specify a lattice polytope::
+
+        sage: from sage.geometry.polyhedron.ppl_lattice_polytope import LatticePolytope_PPL
+        sage: LatticePolytope_PPL((0,0),(1/2,1))
+        Traceback (most recent call last):
+        ...
+        TypeError: no conversion of this rational to integer
+
+        sage: from sage.libs.ppl import point, Generator_System, C_Polyhedron, Linear_Expression, Variable
+        sage: p = point(Linear_Expression([2,3],0), 5);  p
+        point(2/5, 3/5)
+        sage: LatticePolytope_PPL(p)
+        Traceback (most recent call last):
+        ...
+        TypeError: The generator is not a lattice polytope generator.
+
+        sage: P = C_Polyhedron(Generator_System(p));  P
+        A 0-dimensional polyhedron in QQ^2 defined as the convex hull of 1 point
+        sage: LatticePolytope_PPL(P)
+        Traceback (most recent call last):
+        ...
+        TypeError: The polyhedron has non-integral generators.
+    """
+    if len(args)==1 and isinstance(args[0], C_Polyhedron):
+        polyhedron = args[0]
+        #if not polyhedron.is_bounded():
+        #    raise TypeError('The polyhedron is unbounded.')
+        if not all(p.is_point() and p.divisor().is_one() for p in polyhedron.generators()):
+            raise TypeError('The polyhedron has non-integral generators.')
+        return LatticePolytope_PPL_class(polyhedron)
+    vertices = args
+    gs = Generator_System()
+    for v in vertices:
+        if isinstance(v, Generator):
+            if (not v.is_point()) or (not v.divisor().is_one()):
+                raise TypeError('The generator is not a lattice polytope generator.')
+            gs.insert(v)
+        else:
+            gs.insert(point(Linear_Expression(v, 0)))
+    return LatticePolytope_PPL_class(gs)
+    
+
+########################################################################
+class LatticePolytope_PPL_class(C_Polyhedron):
+    """
+    The lattice polytope class.
+
+    EXAMPLES::
+
+        sage: from sage.geometry.polyhedron.ppl_lattice_polytope import LatticePolytope_PPL
+        sage: LatticePolytope_PPL((0,0),(1,0),(0,1))
+        A 2-dimensional polyhedron in QQ^2 defined as the convex hull of 3 points
+    """
+
+    def is_bounded(self):
+        return True
+    
+    @cached_method
+    def n_vertices(self):
+        """
+        Return the number of vertices.
+        
+        EXAMPLES::
+
+            sage: from sage.geometry.polyhedron.ppl_lattice_polytope import LatticePolytope_PPL
+            sage: LatticePolytope_PPL((0,0,0), (1,0,0), (0,1,0)).n_vertices()
+            3
+        """
+        return len(self.minimized_generators())
+
+    @cached_method
+    def is_simplex(self):
+        r"""
+        Return whether the polyhedron is a simplex.
+        
+        EXAMPLES::
+
+            sage: from sage.geometry.polyhedron.ppl_lattice_polytope import LatticePolytope_PPL
+            sage: LatticePolytope_PPL((0,0,0), (1,0,0), (0,1,0)).is_simplex()
+            True
+        """
+        return self.affine_dimension()+1==self.n_vertices()
+
+    @cached_method
+    def bounding_box(self):
+        r"""
+        Return the coordinates of a rectangular box containing the non-empty polytope.
+
+        OUTPUT:
+
+        A pair of tuples ``(box_min, box_max)`` where ``box_min`` are
+        the coordinates of a point bounding the coordinates of the
+        polytope from below and ``box_max`` bounds the coordinates
+        from above.
+
+        EXAMPLES::
+
+            sage: from sage.geometry.polyhedron.ppl_lattice_polytope import LatticePolytope_PPL
+            sage: LatticePolytope_PPL((0,0),(1,0),(0,1)).bounding_box()
+            ((0, 0), (1, 1))
+        """
+        box_min = []
+        box_max = []
+        if self.is_empty():
+            raise ValueError('Empty polytope is not allowed')
+        for i in range(0, self.space_dimension()):
+            x = Variable(i)
+            coords = [ v.coefficient(x) for v in self.generators() ]
+            max_coord = max(coords)
+            min_coord = min(coords)
+            box_max.append(max_coord)
+            box_min.append(min_coord)
+        return (tuple(box_min), tuple(box_max))
+    
+    @cached_method
+    def n_integral_points(self):
+        """
+        Return the number of integral points.
+
+        OUTPUT:
+
+        Integer.
+
+        EXAMPLES::
+
+            sage: from sage.geometry.polyhedron.ppl_lattice_polytope import LatticePolytope_PPL
+            sage: LatticePolytope_PPL((0,0),(1,0),(0,1)).n_integral_points()
+            3
+        """
+        if self.is_empty():
+            return tuple()
+        box_min, box_max = self.bounding_box() 
+        from sage.geometry.integral_points import rectangular_box_points
+        return rectangular_box_points(box_min, box_max, self, count_only=True)
+
+    @cached_method
+    def integral_points(self):
+        r"""
+        Return the integral points in the polyhedron.
+
+        Uses the naive algorithm (iterate over a rectangular bounding
+        box).
+
+        OUTPUT:
+        
+        The list of integral points in the polyhedron. If the
+        polyhedron is not compact, a ``ValueError`` is raised.
+
+        EXAMPLES::
+        
+            sage: from sage.geometry.polyhedron.ppl_lattice_polytope import LatticePolytope_PPL
+            sage: LatticePolytope_PPL((-1,-1),(1,0),(1,1),(0,1)).integral_points()
+            ((-1, -1), (0, 0), (0, 1), (1, 0), (1, 1))
+
+            sage: simplex = LatticePolytope_PPL((1,2,3), (2,3,7), (-2,-3,-11))
+            sage: simplex.integral_points()
+            ((-2, -3, -11), (0, 0, -2), (1, 2, 3), (2, 3, 7))
+
+        The polyhedron need not be full-dimensional::
+
+            sage: simplex = LatticePolytope_PPL((1,2,3,5), (2,3,7,5), (-2,-3,-11,5))
+            sage: simplex.integral_points()
+            ((-2, -3, -11, 5), (0, 0, -2, 5), (1, 2, 3, 5), (2, 3, 7, 5))
+
+            sage: point = LatticePolytope_PPL((2,3,7))
+            sage: point.integral_points()
+            ((2, 3, 7),)
+
+            sage: empty = LatticePolytope_PPL()
+            sage: empty.integral_points()
+            ()
+
+        Here is a simplex where the naive algorithm of running over
+        all points in a rectangular bounding box no longer works fast
+        enough::
+
+            sage: v = [(1,0,7,-1), (-2,-2,4,-3), (-1,-1,-1,4), (2,9,0,-5), (-2,-1,5,1)]
+            sage: simplex = LatticePolytope_PPL(*v); simplex
+            A 4-dimensional polyhedron in QQ^4 defined as the convex hull of 5 points
+            sage: len(simplex.integral_points())
+            49
+
+        Finally, the 3-d reflexive polytope number 4078::
+
+            sage: v = [(1,0,0), (0,1,0), (0,0,1), (0,0,-1), (0,-2,1), 
+            ...        (-1,2,-1), (-1,2,-2), (-1,1,-2), (-1,-1,2), (-1,-3,2)]
+            sage: P = LatticePolytope_PPL(*v)
+            sage: pts1 = P.integral_points()                     # Sage's own code
+            sage: pts2 = LatticePolytope(v).points().columns()   # PALP
+            sage: for p in pts1: p.set_immutable()
+            sage: for p in pts2: p.set_immutable()
+            sage: set(pts1) == set(pts2)
+            True
+
+            sage: timeit('Polyhedron(v).integral_points()')   # random output
+            sage: timeit('LatticePolytope(v).points()')       # random output
+            sage: timeit('LatticePolytope_PPL(*v).integral_points()')       # random output
+        """
+        if self.is_empty():
+            return tuple()
+        box_min, box_max = self.bounding_box() 
+        from sage.geometry.integral_points import rectangular_box_points
+        points = rectangular_box_points(box_min, box_max, self)
+        if not self.n_integral_points.is_in_cache():
+            self.n_integral_points.set_cache(len(points))
+        return points
+    
+    @cached_method
+    def _integral_points_saturating(self):
+        """
+        Return the integral points together with information about
+        which inequalities are saturated.
+
+        See :func:`~sage.geometry.integral_points.rectangular_box_points`.
+
+        OUTPUT:
+        
+        A tuple of pairs (one for each integral point) consisting of a
+        pair ``(point, Hrep)``, where ``point`` is the coordinate
+        vector of the intgeral point and ``Hrep`` is the set of
+        indices of the :meth:`minimized_constraints` that are
+        saturated at the point.
+
+        EXAMPLES::
+         
+            sage: from sage.geometry.polyhedron.ppl_lattice_polytope import LatticePolytope_PPL
+            sage: quad = LatticePolytope_PPL((-1,-1),(0,1),(1,0),(1,1))
+            sage: quad._integral_points_saturating()
+            (((-1, -1), frozenset([0, 1])),
+             ((0, 0), frozenset([])), 
+             ((0, 1), frozenset([0, 3])), 
+             ((1, 0), frozenset([1, 2])), 
+             ((1, 1), frozenset([2, 3])))
+        """
+        if self.is_empty():
+            return tuple()
+        box_min, box_max = self.bounding_box() 
+        from sage.geometry.integral_points import rectangular_box_points
+        points= rectangular_box_points(box_min, box_max, self, return_saturated=True)
+        if not self.n_integral_points.is_in_cache():
+            self.n_integral_points.set_cache(len(points))
+        if not self.integral_points.is_in_cache():
+            self.integral_points.set_cache(tuple(p[0] for p in points))
+        return points
+
+    @cached_method
+    def integral_points_not_interior_to_facets(self):
+        """
+        Return the integral points not interior to facets
+
+        EXAMPLES::
+         
+            sage: from sage.geometry.polyhedron.ppl_lattice_polytope import LatticePolytope_PPL
+            sage: square = LatticePolytope_PPL((-1,-1),(-1,1),(1,-1),(1,1))
+            sage: square.n_integral_points()
+            9
+            sage: square.integral_points_not_interior_to_facets()
+            ((-1, -1), (-1, 1), (0, 0), (1, -1), (1, 1))
+        """
+        n = 1 + self.space_dimension() - self.affine_dimension()
+        return tuple(p[0] for p in self._integral_points_saturating() if len(p[1])!=n)
+
+    @cached_method
+    def vertices(self):
+        """
+        Return the vertices as a tuple of `\ZZ`-vectors.
+        
+        EXAMPLES::
+
+            sage: from sage.geometry.polyhedron.ppl_lattice_polytope import LatticePolytope_PPL
+            sage: p = LatticePolytope_PPL((-9,-6,-1,-1),(0,0,0,1),(0,0,1,0),(0,1,0,0),(1,0,0,0))
+            sage: p.vertices()
+            ((-9, -6, -1, -1), (0, 0, 0, 1), (0, 0, 1, 0), (0, 1, 0, 0), (1, 0, 0, 0))
+            sage: p.minimized_generators()
+            Generator_System {point(-9/1, -6/1, -1/1, -1/1), point(0/1, 0/1, 0/1, 1/1), 
+            point(0/1, 0/1, 1/1, 0/1), point(0/1, 1/1, 0/1, 0/1), point(1/1, 0/1, 0/1, 0/1)}
+        """
+        d = self.space_dimension()
+        v = vector(ZZ, d)
+        points = []
+        for g in self.minimized_generators():
+            for i in range(0,d):
+                v[i] = g.coefficient(Variable(i))
+            v_copy = copy.copy(v)
+            v_copy.set_immutable()
+            points.append(v_copy)
+        return tuple(points)
+
+    @cached_method
+    def is_full_dimensional(self):
+        return self.affine_dimension() == self.space_dimension()
+
+    def fibration_generator(self, dim):
+        """
+        Generate the lattice polytope fibrations.
+        
+        For the purposes of this function, a lattice polytope fiber is
+        a sub-lattice polytope. Projecting the plane spanned by the
+        subpolytope to a point yields another lattice polytope, the
+        base of the fibration.
+
+        INPUT:
+        
+        - ``dim`` -- integer. The dimension of the lattice polytope
+          fiber.
+
+        OUTPUT:
+
+        A generator yielding the distinct lattice polytope fibers of
+        given dimension.
+        
+        EXAMPLES::
+
+            sage: from sage.geometry.polyhedron.ppl_lattice_polytope import LatticePolytope_PPL
+            sage: p = LatticePolytope_PPL((-9,-6,-1,-1),(0,0,0,1),(0,0,1,0),(0,1,0,0),(1,0,0,0))
+            sage: list( p.fibration_generator(2) )
+            [A 2-dimensional polyhedron in QQ^4 defined as the convex hull of 3 points]
+        """        
+        assert self.is_full_dimensional()
+        codim = self.space_dimension() - dim
+        # "points" are the potential vertices of the fiber. They are
+        # in the $codim$-skeleton of the polytope, which is contained
+        # in the points that saturate at least $dim$ equations.
+        points = [ p for p in self._integral_points_saturating() if len(p[1])>=dim ]
+        points = sorted(points, key=lambda x:len(x[1]))
+
+        # iterate over point combinations subject to all points being on one facet.
+        def point_combinations_iterator(n, i0=0, saturated=None):
+            for i in range(i0, len(points)):
+                p, ieqs = points[i]
+                if saturated is None:
+                    saturated_ieqs = ieqs
+                else:
+                    saturated_ieqs = saturated.intersection(ieqs)
+                if len(saturated_ieqs)==0:
+                    continue
+                if n == 1:
+                    yield [i]
+                else:
+                    for c in point_combinations_iterator(n-1, i+1, saturated_ieqs):
+                        yield [i] + c
+
+        point_lines = [ line(Linear_Expression(p[0].list(),0)) for p in points ]
+        origin = point()
+        fibers = set()
+        gs = Generator_System()
+        for indices in point_combinations_iterator(dim):
+            gs.clear()
+            gs.insert(origin)
+            for i in indices:
+                gs.insert(point_lines[i])
+            plane = C_Polyhedron(gs)
+            if plane.affine_dimension() != dim:
+                continue
+            plane.intersection_assign(self)
+            if (not self.is_full_dimensional()) and (plane.affine_dimension() != dim):
+                continue
+            try:
+                fiber = LatticePolytope_PPL(plane)
+            except TypeError:   # not a lattice polytope
+                continue
+            fiber_vertices = tuple(sorted(fiber.vertices()))
+            if fiber_vertices not in fibers:
+                yield fiber
+                fibers.update([fiber_vertices])
+
+    def pointsets_mod_automorphism(self, pointsets):
+        """
+        Return ``pointsets`` modulo the automorphisms of ``self``.
+        
+        INPUT:
+
+        - ``polytopes`` a tuple/list/iterable of subsets of the integral points of ``self``.
+
+        OUTPUT:
+        
+        Representatives of the point sets modulo the :meth:`lattice_automorphism_group` of ``self``.
+        
+        EXAMPLES::
+
+            sage: from sage.geometry.polyhedron.ppl_lattice_polytope import LatticePolytope_PPL
+            sage: square = LatticePolytope_PPL((-1,-1),(-1,1),(1,-1),(1,1))
+            sage: fibers = [ f.vertices() for f in square.fibration_generator(1) ]
+            sage: square.pointsets_mod_automorphism(fibers)
+            (frozenset([(1, 1), (-1, -1)]), frozenset([(1, 0), (-1, 0)]))
+
+            sage: cell24 = LatticePolytope_PPL(
+            ...   (1,0,0,0),(0,1,0,0),(0,0,1,0),(0,0,0,1),(1,-1,-1,1),(0,0,-1,1),          
+            ...   (0,-1,0,1),(-1,0,0,1),(1,0,0,-1),(0,1,0,-1),(0,0,1,-1),(-1,1,1,-1),
+            ...   (1,-1,-1,0),(0,0,-1,0),(0,-1,0,0),(-1,0,0,0),(1,-1,0,0),(1,0,-1,0),
+            ...   (0,1,1,-1),(-1,1,1,0),(-1,1,0,0),(-1,0,1,0),(0,-1,-1,1),(0,0,0,-1))
+            sage: fibers = [ f.vertices() for f in cell24.fibration_generator(2) ]
+            sage: cell24.pointsets_mod_automorphism(fibers)   # long time
+            (frozenset([(1, 0, -1, 0), (-1, 0, 1, 0), (0, -1, -1, 1), (0, 1, 1, -1)]), 
+             frozenset([(-1, 0, 0, 0), (1, 0, 0, 0), (0, 0, 0, 1), 
+                        (1, 0, 0, -1), (0, 0, 0, -1), (-1, 0, 0, 1)]))
+            
+        """
+        points = set()
+        for ps in pointsets:
+            points.update(ps)
+        points = tuple(points)
+        Aut = self.lattice_automorphism_group(points)
+        indexsets = set([ frozenset([points.index(p) for p in ps]) for ps in pointsets ])
+        print indexsets
+        orbits = []
+        while len(indexsets)>0:
+            idx = indexsets.pop()
+            orbits.append(frozenset([points[i] for i in idx]))
+            for g in Aut:
+                g_idx = frozenset([g(i+1)-1 for i in idx])
+                indexsets.difference_update([g_idx])
+        return tuple(orbits)
+                                
+    @cached_method
+    def ambient_space(self):
+        from sage.modules.free_module import FreeModule
+        return FreeModule(ZZ, self.space_dimension())
+
+    @cached_method
+    def affine_space(self):
+        return self.ambient_space().span(self.vertices()).saturation()
+
+    def affine_lattice_polytope(self):
+        """
+        EXAMPLES::
+        
+            sage: from sage.geometry.polyhedron.ppl_lattice_polytope import LatticePolytope_PPL
+            sage: poly = LatticePolytope_PPL((-9,-6,0,0),(0,1,0,0),(1,0,0,0));  poly
+            A 2-dimensional polyhedron in QQ^4 defined as the convex hull of 3 points
+            sage: poly.affine_lattice_polytope()
+            A 2-dimensional polyhedron in QQ^2 defined as the convex hull of 3 points
+        """
+        V = self.affine_space()
+        vertices = [ V.coordinates(v) for v in self.vertices() ]
+        return LatticePolytope_PPL(*vertices)
+
+    @cached_method
+    def base_projection(self, fiber):
+        """
+        EXAMPLES::
+        
+            sage: from sage.geometry.polyhedron.ppl_lattice_polytope import LatticePolytope_PPL
+            sage: poly = LatticePolytope_PPL((-9,-6,-1,-1),(0,0,0,1),(0,0,1,0),(0,1,0,0),(1,0,0,0))
+            sage: fiber = poly.fibration_generator(2).next()
+            sage: poly.base_projection(fiber)
+            Finitely generated module V/W over Integer Ring with invariants (0, 0)
+        """
+        return self.ambient_space().quotient(fiber.affine_space())
+
+    def base_rays(self, fiber, points):
+        """
+        Return the primitive lattice vectors that generate the
+        direction given by the base projection of points.
+
+        EXAMPLES::
+        
+            sage: from sage.geometry.polyhedron.ppl_lattice_polytope import LatticePolytope_PPL
+            sage: poly = LatticePolytope_PPL((-9,-6,-1,-1),(0,0,0,1),(0,0,1,0),(0,1,0,0),(1,0,0,0))
+            sage: fiber = poly.fibration_generator(2).next()
+            sage: poly.base_rays(fiber, poly.integral_points_not_interior_to_facets())
+            ((-1, -1), (0, 1), (1, 0))
+
+            sage: p = LatticePolytope_PPL((1,0),(1,2),(-1,0))
+            sage: f = LatticePolytope_PPL((1,0),(-1,0))
+            sage: p.base_rays(f, p.integral_points())
+            ((1),)
+        """
+        quo = self.base_projection(fiber)
+        vertices = []
+        for p in points:
+            v = vector(ZZ,quo(p))
+            if v.is_zero():
+                continue
+            d =  GCD_list(v.list())
+            if d>1:
+                for i in range(0,v.degree()):
+                    v[i] /= d
+            v.set_immutable()
+            vertices.append(v)
+        return tuple(uniq(vertices))
+        
+    @cached_method
+    def has_IP_property(self):
+        """
+        EXAMPLES::
+        
+            sage: from sage.geometry.polyhedron.ppl_lattice_polytope import LatticePolytope_PPL
+            sage: LatticePolytope_PPL((-1,-1),(0,1),(1,0)).has_IP_property()
+            True
+            sage: LatticePolytope_PPL((-1,-1),(1,1)).has_IP_property()
+            False
+        """
+        origin = C_Polyhedron(point(0*Variable(self.space_dimension())))
+        is_included = Poly_Con_Relation.is_included()
+        saturates = Poly_Con_Relation.saturates()
+        for c in self.constraints():
+            rel = origin.relation_with(c)
+            if (not rel.implies(is_included)) or rel.implies(saturates):
+                return False
+        return True
+            
+    def _is_isomorphic_P2(self):
+        if not self.space_dimension() == 2: return False
+        rays = self.vertices()
+        if len(rays) != 3: return False
+        if not sum(rays).is_zero(): return False
+        if abs(matrix(ZZ, [rays[0], rays[1]]).det()) != 1: return False
+        if abs(matrix(ZZ, [rays[0], rays[2]]).det()) != 1: return False
+        if abs(matrix(ZZ, [rays[1], rays[2]]).det()) != 1: return False
+        return True
+
+    def is_isomorphic_to(self, polytope):
+        """
+        EXAMPLES::
+
+            sage: from sage.geometry.polyhedron.ppl_lattice_polytope import LatticePolytope_PPL
+            sage: LatticePolytope_PPL((-1,-1),(0,1),(1,0)).is_isomorphic_to('P2')
+            True
+        """
+        if isinstance(polytope, basestring):
+            if polytope.lower() == 'p2':
+                return self._is_isomorphic_P2()
+        raise ValueError('Cannot compare polytopes.')
+
+    @cached_method
+    def restricted_automorphism_group(self):
+        r"""
+        Return the restricted automorphism group.
+
+        First, let the linear automorphism group be the subgroup of
+        the Euclidean group `E(d) = GL(d,\RR) \ltimes \RR^d`
+        preserving the `d`-dimensional polyhedron. The Euclidean group
+        acts in the usual way `\vec{x}\mapsto A\vec{x}+b` on the
+        ambient space. The restricted automorphism group is the
+        subgroup of the linear automorphism group generated by
+        permutations of vertices. If the polytope is full-dimensional,
+        it is equal to the full (unrestricted) automorphism group.
+
+        OUTPUT:
+        
+        A
+        :class:`PermutationGroup<sage.groups.perm_gps.permgroup.PermutationGroup_generic>`.
+        
+        Note that in Sage, permutation groups always act on positive
+        integers while ``self.minimized_generators()`` is indexed by
+        nonnegative integers. The indexing of the permutation group is
+        chosen to be shifted by ``+1``.
+
+        REFERENCES:
+
+        ..  [BSS]
+            David Bremner, Mathieu Dutour Sikiric, Achill Schuermann:
+            Polyhedral representation conversion up to symmetries.
+            http://arxiv.org/abs/math/0702239
+
+        EXAMPLES::
+
+            sage: from sage.geometry.polyhedron.ppl_lattice_polytope import LatticePolytope_PPL
+            sage: cell24 = LatticePolytope_PPL(
+            ...   (1,0,0,0),(0,1,0,0),(0,0,1,0),(0,0,0,1),(1,-1,-1,1),(0,0,-1,1),          
+            ...   (0,-1,0,1),(-1,0,0,1),(1,0,0,-1),(0,1,0,-1),(0,0,1,-1),(-1,1,1,-1),
+            ...   (1,-1,-1,0),(0,0,-1,0),(0,-1,0,0),(-1,0,0,0),(1,-1,0,0),(1,0,-1,0),
+            ...   (0,1,1,-1),(-1,1,1,0),(-1,1,0,0),(-1,0,1,0),(0,-1,-1,1),(0,0,0,-1))
+
+            
+            sage: from sage.geometry.polyhedron.ppl_lattice_polytope import LatticePolytope_PPL
+            sage: Z3square = LatticePolytope_PPL((0,0), (1,2), (2,1), (3,3))
+            sage: Z3square.restricted_automorphism_group()
+            Permutation Group with generators [(2,3), (1,2)(3,4), (1,4)]
+        """
+        if not self.is_full_dimensional():
+            return self.affine_lattice_polytope().restricted_automorphism_group()
+        
+        from sage.groups.perm_gps.permgroup import PermutationGroup
+        from sage.graphs.graph import Graph
+        # good coordinates for the vertices
+        v_list = []
+        for v in self.minimized_generators():
+            assert v.divisor().is_one()
+            v_coords = (1,) + v.coefficients()
+            v_list.append(vector(v_coords))
+
+        # Finally, construct the graph
+        Qinv = sum( v.column() * v.row() for v in v_list ).inverse()
+        G = Graph(dense=True)
+        for i in range(0,len(v_list)):
+            for j in range(i+1,len(v_list)):
+                v_i = v_list[i]
+                v_j = v_list[j]
+                G.add_edge(i,j, v_i * Qinv * v_j)
+        group, node_dict = G.automorphism_group(edge_labels=True, translation=True)
+
+        # Relabel the permutation group
+        perm_to_vertex = dict( (i,v+1) for v,i in node_dict.items() )
+        group = PermutationGroup([ [ tuple([ perm_to_vertex[i] for i in cycle ])
+                                     for cycle in generator.cycle_tuples() ]
+                                   for generator in group.gens() ])
+        return group
+
+    @cached_method
+    def lattice_automorphism_group(self, points=None):
+        """
+        The integral subgroup of the restricted automorphism group.
+
+        INPUT:
+
+        - ``points`` -- A list of coordinate vectors or ``None``
+          (default). If specified, the points must form complete
+          orbits under the lattice automorphism group.
+
+        OUTPUT:
+
+        The integral subgroup of the restricted automorphism group.
+
+        If ``points`` are specified, the permutation group acting on
+        them is returned.
+
+        EXAMPLES::
+
+            sage: from sage.geometry.polyhedron.ppl_lattice_polytope import LatticePolytope_PPL
+            sage: Z3square = LatticePolytope_PPL((0,0), (1,2), (2,1), (3,3))
+            sage: Z3square.restricted_automorphism_group()
+            Permutation Group with generators [(2,3), (1,2)(3,4), (1,4)]
+            sage: len(_)
+            8
+
+            sage: Z3square.lattice_automorphism_group()
+            Permutation Group with generators [(), (2,3), (1,4), (1,4)(2,3)]
+            sage: len(_)
+            4
+
+            sage: points = Z3square.integral_points();  points
+            ((0, 0), (1, 1), (1, 2), (2, 1), (2, 2), (3, 3))
+            sage: Z3square.lattice_automorphism_group(points)
+            Permutation Group with generators [(), (3,4), (1,6)(2,5), (1,6)(2,5)(3,4)]
+        """
+        if not self.is_full_dimensional():
+            return self.affine_lattice_polytope().lattice_automorphism_group()
+
+        if points is not None:
+            points = [ vector(ZZ, [1]+v.list()) for v in points ]
+
+        vertices = [ vector(ZZ, [1]+v.list()) for v in self.vertices() ]
+        pivots = matrix(ZZ, vertices).pivot_rows()
+        basis = matrix(ZZ, [ vertices[i] for i in pivots ])
+        Mat_ZZ = basis.parent()
+        basis_inverse = basis.inverse()
+
+        from sage.groups.perm_gps.permgroup import PermutationGroup
+        from sage.groups.perm_gps.permgroup_element import PermutationGroupElement
+        lattice_gens = []
+        for g in self.restricted_automorphism_group():
+            image = matrix(ZZ, [ vertices[g(i+1)-1] for i in pivots ])
+            m = basis_inverse*image
+            if m not in Mat_ZZ:
+                continue
+            if points is None:
+                lattice_gens.append(g)
+            else:
+                perm_list = [ points.index(points[i]*m)+1 for i in range(0,len(points))]
+                lattice_gens.append(PermutationGroupElement(perm_list))
+        return PermutationGroup(lattice_gens)
+
+
+
+
+
+########################################################################
+class LatticePolytope_4d_PPL_class(LatticePolytope_PPL_class):
+    pass
+    
diff --git a/sage/libs/ppl.pyx b/sage/libs/ppl.pyx
--- a/sage/libs/ppl.pyx
+++ b/sage/libs/ppl.pyx
@@ -4578,6 +4578,23 @@
         """
         return self.thisptr.OK()
 
+    
+    def __len__(self):
+        """
+        Return the number of generators in the system.
+
+            sage: from sage.libs.ppl import Variable, Generator_System, point
+            sage: x = Variable(0)
+            sage: y = Variable(1)
+            sage: gs = Generator_System()
+            sage: gs.insert(point(3*x+2*y))
+            sage: gs.insert(point(x))
+            sage: gs.insert(point(y))
+            sage: len(gs)
+            3
+        """
+        return sum([1 for g in self])
+
 
     def __iter__(self):
         """
@@ -5554,6 +5571,22 @@
         """
         return self.thisptr.OK()
 
+    
+    def __len__(self):
+        """
+        Return the number of constraints in the system.
+
+        EXAMPLES::
+
+            sage: from sage.libs.ppl import Variable, Constraint_System
+            sage: x = Variable(0)
+            sage: cs = Constraint_System( x>0 )
+            sage: cs.insert( x<1 )
+            sage: len(cs)
+            2
+        """
+        return sum([1 for c in self])
+
 
     def __iter__(self):
         """
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.