File: polyhedralfan.cpp

package info (click to toggle)
gfan 0.5%2Bdfsg-5
  • links: PTS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 8,296 kB
  • ctags: 5,612
  • sloc: cpp: 39,675; makefile: 453; sh: 1
file content (1926 lines) | stat: -rw-r--r-- 56,582 bytes parent folder | download | duplicates (2)
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
#include <sstream>
#include "polyhedralfan.h"
#include "reversesearch.h"
#include "wallideal.h"
#include "buchberger.h"
#include "printer.h"
#include "timer.h"
#include "symmetry.h"
#include "polymakefile.h"
#include "symmetriccomplex.h"
#include "linalg.h"
#include "lp.h"
#include "codimoneconnectedness.h"
#include "symmetrictraversal.h"
#include "traverser_groebnerfan.h"
#include "log.h"

static Timer polyhedralFanRefinementTimer("Polyhedral fan refinement",1);

PolyhedralFan::PolyhedralFan(int ambientDimension):
  n(ambientDimension)
{
}


PolyhedralFan PolyhedralFan::fullSpace(int n)
{
  PolyhedralFan ret(n);

  PolyhedralCone temp(n);
  temp.canonicalize();
  ret.cones.insert(temp);

  return ret;
}


PolyhedralFan PolyhedralFan::halfSpace(int n, int i)
{
  assert(0<=i);
  assert(i<n);
  PolyhedralFan ret(n);

  IntegerVector v(n);
  v[i]=-1;
  IntegerVectorList l;
  IntegerVectorList empty;
  l.push_back(v);
  ret.cones.insert(PolyhedralCone(l,empty,n));

  return ret;
}


PolyhedralFan PolyhedralFan::facetsOfCone(PolyhedralCone const &c)
{
  PolyhedralCone C(c);
  C.canonicalize();
  PolyhedralFan ret(C.ambientDimension());

  IntegerVectorList halfSpaces=C.getHalfSpaces();

  for(IntegerVectorList::const_iterator i=halfSpaces.begin();i!=halfSpaces.end();i++)
    {
      IntegerVectorList a;
      IntegerVectorList b;
      b.push_back(*i);
      PolyhedralCone n=intersection(PolyhedralCone(a,b),c);
      n.canonicalize();
      ret.cones.insert(n);
    }
  return ret;
}

PolyhedralFan PolyhedralFan::complementOfCone(PolyhedralCone const &c, bool includec)
{
  PolyhedralCone C=c;
  C.canonicalize();
  IntegerVectorList inequalities=C.getHalfSpaces();
  IntegerVectorList equations=C.getEquations();

  for(IntegerVectorList::const_iterator i=equations.begin();i!=equations.end();i++)
    inequalities.push_back(*i);

  int n=C.ambientDimension();

  PolyhedralFan ret=PolyhedralFan::fullSpace(n);
  for(IntegerVectorList::const_iterator i=inequalities.begin();i!=inequalities.end();i++)
    {
      PolyhedralFan temp(C.ambientDimension());
      for(int j=-1;j<2;j+=2)
	{
	  IntegerVectorList inequality;
	  inequality.push_back(j* *i);
	  IntegerVectorList empty;
	  PolyhedralCone tempC(inequality,empty,n);
	  tempC.canonicalize();
	  temp.insert(tempC);
	}
      ret=refinement(ret,temp);
    }
  if(!includec)ret.remove(C);
  return ret;
}

PolyhedralFan PolyhedralFan::bergmanOfPrincipalIdeal(Polynomial const &p1)
{
  PolynomialRing theRing=p1.getRing();
  PolynomialRing theSecondRing=theRing.withVariablesAppended("H");
  Polynomial p=p1.homogenization(theSecondRing);
  PolyhedralFan ret(p1.getNumberOfVariables());
  PolynomialSet g(theSecondRing);
  g.push_back(p);
  buchberger(&g,LexicographicTermOrder());

  EnumerationTargetCollector gfan;
  LexicographicTermOrder myTermOrder;
  ReverseSearch rs(myTermOrder);

  rs.setEnumerationTarget(&gfan);

  rs.enumerate(g);

  PolynomialSetList theList=gfan.getList();
  for(PolynomialSetList::const_iterator i=theList.begin();i!=theList.end();i++)
    {
      //      AsciiPrinter(Stderr).printPolynomialSet(*i);
      IntegerVectorList inequalities=wallInequalities(*i);
      IntegerVectorList f=wallFlipableNormals(*i,true);
      for(IntegerVectorList::const_iterator j=f.begin();j!=f.end();j++)
	{
	  //	  AsciiPrinter(Stderr).printVector(*j);
	  if(myTermOrder(*j,*j-*j))
	    {
	      IntegerVectorList equalities;
	      equalities.push_back(*j);
	      PolyhedralCone c=PolyhedralCone(inequalities,equalities).withLastCoordinateRemoved();
	      c.canonicalize();
	      c.setLinearForm(i->begin()->getMarked().m.exponent.subvector(0,p1.getNumberOfVariables()));
	      c.setMultiplicity(gcdOfVector(j->subvector(0,j->size()-1)));
	      ret.cones.insert(c);
	    }
	}
    }

  return ret;
}


PolyhedralFan PolyhedralFan::normalFanOfNewtonPolytope(Polynomial const &p1)
{
  PolynomialRing theRing=p1.getRing();
  PolynomialRing theSecondRing=theRing.withVariablesAppended("H");
  Polynomial p=p1.homogenization(theSecondRing);
  PolyhedralFan ret(p1.getNumberOfVariables());
  PolynomialSet g(theSecondRing);
  //  PolynomialSet g(theRing);//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  g.push_back(p);
  buchberger(&g,LexicographicTermOrder());

  EnumerationTargetCollector gfan;
/*  {//old enumeration strategy
  LexicographicTermOrder myTermOrder;
  ReverseSearch rs(myTermOrder);

  rs.setEnumerationTarget(&gfan);

  rs.enumerate(g);
  }
*/
  {//new enumeration strategy
    GroebnerFanTraverser traverser(g);
    traverser.setIsKnownToBeComplete(true);
    TargetGlue target(gfan);
    symmetricTraverse(traverser,target);
  }

  PolynomialSetList theList=gfan.getList();
  for(PolynomialSetList::const_iterator i=theList.begin();i!=theList.end();i++)
    {
      IntegerVectorList inequalities=wallInequalities(*i);
      IntegerVectorList equalities;

      PolyhedralCone c=PolyhedralCone(inequalities,equalities).withLastCoordinateRemoved();
      c.canonicalize();
      c.setLinearForm(i->begin()->getMarked().m.exponent.subvector(0,c.ambientDimension()));
      ret.cones.insert(c);
    }

  return ret;
}


void PolyhedralFan::print(class Printer *p)const
{
  p->printString("Printing PolyhedralFan");
  p->printNewLine();
  p->printString("Ambient dimension: ");
  p->printInteger(n);
  p->printNewLine();
  p->printString("Number of cones: ");
  p->printInteger(cones.size());
  p->printNewLine();
  for(PolyhedralConeList::const_iterator i=cones.begin();i!=cones.end();i++)
    {
      p->printNewLine();
      p->printPolyhedralCone(*i);
    }
  p->printString("Done printing PolyhedralFan.");
  p->printNewLine();
}

int PolyhedralFan::getAmbientDimension()const
{
  return n;
}

bool PolyhedralFan::isEmpty()const
{
  return cones.empty();
}

int PolyhedralFan::getMaxDimension()const
{
  assert(!cones.empty());

  return cones.begin()->dimension();
}

int PolyhedralFan::getMinDimension()const
{
  assert(!cones.empty());

  return cones.rbegin()->dimension();
}

PolyhedralFan refinement(const PolyhedralFan &a, const PolyhedralFan &b, int cutOffDimension, bool allowASingleConeOfCutOffDimension)
{
  TimerScope ts(&polyhedralFanRefinementTimer);
  //  fprintf(Stderr,"PolyhedralFan refinement: #A=%i #B=%i\n",a.cones.size(),b.cones.size());
  int conesSkipped=0;
  int numberOfComputedCones=0;
  bool linealityConeFound=!allowASingleConeOfCutOffDimension;
  assert(a.getAmbientDimension()==b.getAmbientDimension());

  PolyhedralFan ret(a.getAmbientDimension());

  for(PolyhedralConeList::const_iterator A=a.cones.begin();A!=a.cones.end();A++)
    for(PolyhedralConeList::const_iterator B=b.cones.begin();B!=b.cones.end();B++)
      {
	PolyhedralCone c=intersection(*A,*B);
	int cdim=c.dimension();
	//	assert(cdim>=linealitySpaceDimension);
	bool thisIsLinealityCone=(cutOffDimension>=cdim);
	if((!thisIsLinealityCone)||(!linealityConeFound))
	  {
	    numberOfComputedCones++;
	    c.canonicalize();
	    ret.cones.insert(c);
	    linealityConeFound=linealityConeFound || thisIsLinealityCone;
	  }
	else
	  {
	    conesSkipped++;
	  }
      }
  //  fprintf(Stderr,"Number of skipped cones: %i, lineality cone found: %i\n",conesSkipped,linealityConeFound);
  //  fprintf(Stderr,"Number of computed cones: %i, number of unique cones: %i\n",numberOfComputedCones,ret.cones.size());

  return ret;
}


PolyhedralFan product(const PolyhedralFan &a, const PolyhedralFan &b)
{
  PolyhedralFan ret(a.getAmbientDimension()+b.getAmbientDimension());

  for(PolyhedralConeList::const_iterator A=a.cones.begin();A!=a.cones.end();A++)
    for(PolyhedralConeList::const_iterator B=b.cones.begin();B!=b.cones.end();B++)
      ret.insert(product(*A,*B));

  return ret;
}


IntegerVectorList PolyhedralFan::getRays(int dim)
{
  IntegerVectorList ret;
  for(PolyhedralConeList::iterator i=cones.begin();i!=cones.end();i++)
    {
      if(i->dimension()==dim)
	ret.push_back(i->getRelativeInteriorPoint());
    }
  return ret;
}


IntegerVectorList PolyhedralFan::getRelativeInteriorPoints()
{
  IntegerVectorList ret;
  for(PolyhedralConeList::iterator i=cones.begin();i!=cones.end();i++)
    {
      ret.push_back(i->getRelativeInteriorPoint());
    }
  return ret;
}


PolyhedralCone const& PolyhedralFan::highestDimensionalCone()const
{
  return *cones.rbegin();
}

void PolyhedralFan::insert(PolyhedralCone const &c)
{
  cones.insert(c);
}


void PolyhedralFan::insertFacetsOfCone(PolyhedralCone const &c)
{
  PolyhedralFan facets=facetsOfCone(c);
  for(PolyhedralConeList::const_iterator i=facets.cones.begin();i!=facets.cones.end();i++)insert(*i);
}


void PolyhedralFan::remove(PolyhedralCone const &c)
{
  cones.erase(c);
}

void PolyhedralFan::removeAllExcept(int a)
{
  PolyhedralConeList::iterator i=cones.begin();
  while(a>0)
    {
      if(i==cones.end())return;
      i++;
      a--;
    }
  cones.erase(i,cones.end());
}

void PolyhedralFan::removeAllLowerDimensional()
{
  if(!cones.empty())
    {
      int d=getMaxDimension();
      PolyhedralConeList::iterator i=cones.begin();
      while(i!=cones.end() && i->dimension()==d)i++;
      cones.erase(i,cones.end());
    }
}


PolyhedralFan PolyhedralFan::facetComplex()const
{
  //  fprintf(Stderr,"Computing facet complex...\n");
  PolyhedralFan ret(n);

  for(PolyhedralConeList::iterator i=cones.begin();i!=cones.end();i++)
    {
      PolyhedralFan a=facetsOfCone(*i);
      for(PolyhedralConeList::const_iterator j=a.cones.begin();j!=a.cones.end();j++)
	ret.insert(*j);
    }
  //  fprintf(Stderr,"Done computing facet complex.\n");
  return ret;
}


PolyhedralFan PolyhedralFan::fullComplex()const
{
  PolyhedralFan ret=*this;

  while(1)
    {
      log2 debug<<"looping";
      bool doLoop=false;
      PolyhedralFan facets=ret.facetComplex();
      log2 debug<<"number of facets"<<facets.size()<<"\n";
      for(PolyhedralConeList::const_iterator i=facets.cones.begin();i!=facets.cones.end();i++)
	if(!ret.contains(*i))
	  {
	    ret.insert(*i);
	    doLoop=true;
	  }
      if(!doLoop)break;
    }
  return ret;
}


/*
PolyhedralFan PolyhedralFan::facetComplexSymmetry(SymmetryGroup const &sym, bool keepRays, bool dropLinealitySpace)const
{
  log1 fprintf(Stderr,"Computing facet complex...\n");
  PolyhedralFan ret(n);

  if(keepRays)
    for(PolyhedralConeList::iterator i=cones.begin();i!=cones.end();i++)
      if(i->dimension()==i->dimensionOfLinealitySpace()+1)ret.insert(*i);

  for(PolyhedralConeList::iterator i=cones.begin();i!=cones.end();i++)
    {
      PolyhedralFan a=facetsOfCone(*i);
      for(PolyhedralConeList::const_iterator j=a.cones.begin();j!=a.cones.end();j++)
	{
	  if((!dropLinealitySpace) || j->dimension()!=j->dimensionOfLinealitySpace())
	    {
	      IntegerVector v=j->getRelativeInteriorPoint();
	      bool alreadyInRet=false;
	      for(SymmetryGroup::ElementContainer::const_iterator k=sym.elements.begin();k!=sym.elements.end();k++)
		{
		  IntegerVector u=SymmetryGroup::compose(*k,v);
		  if(!j->containsRelatively(u))
		    {
		      for(PolyhedralConeList::const_iterator l=ret.cones.begin();l!=ret.cones.end();l++)
			if(l->containsRelatively(u))alreadyInRet=true;
		    }
		}
	      if(!alreadyInRet)ret.insert(*j);
	    }
	}
    }
  log1 fprintf(Stderr,"Done computing facet complex.\n");
  return ret;
}
*/

PolyhedralFan PolyhedralFan::facetComplexSymmetry(SymmetryGroup const &sym, bool keepRays, bool dropLinealitySpace)const
{
  log1 fprintf(Stderr,"Computing facet complex...\n");
  PolyhedralFan ret(n);

  vector<IntegerVector> relIntTable;
  vector<int> dimensionTable;

  if(keepRays)
    for(PolyhedralConeList::iterator i=cones.begin();i!=cones.end();i++)
      if(i->dimension()==i->dimensionOfLinealitySpace()+1)
	{
	  relIntTable.push_back(i->getRelativeInteriorPoint());
	  dimensionTable.push_back(i->dimension());
	  ret.insert(*i);
	}

  for(PolyhedralConeList::iterator i=cones.begin();i!=cones.end();i++)
    {
      int iDim=i->dimension();
      if(dropLinealitySpace && (i->dimension()==i->dimensionOfLinealitySpace()+1))continue;

      //      i->findFacets();
      IntegerVectorList normals=i->getHalfSpaces();
      for(IntegerVectorList::const_iterator j=normals.begin();j!=normals.end();j++)
	{
	  bool alreadyInRet=false;
	  for(int l=0;l<relIntTable.size();l++)
	    {
	      if(dimensionTable[l]==iDim-1)
		for(SymmetryGroup::ElementContainer::const_iterator k=sym.elements.begin();k!=sym.elements.end();k++)
		  {
		    IntegerVector u=SymmetryGroup::compose(*k,relIntTable[l]);
		    if((dotLong(*j,u)==0) && (i->contains(u)))
		      {
			alreadyInRet=true;
			goto exitLoop;
		      }
		  }
	    }
	exitLoop:
	  if(!alreadyInRet)
	    {
	      IntegerVectorList equations=i->getEquations();
	      IntegerVectorList inequalities=i->getHalfSpaces();
	      equations.push_back(*j);
	      PolyhedralCone c(inequalities,equations,n);
	      c.canonicalize();
	      ret.insert(c);
	      relIntTable.push_back(c.getRelativeInteriorPoint());
	      dimensionTable.push_back(c.dimension());
	    }
	}
    }
  log1 fprintf(Stderr,"Done computing facet complex.\n");
  return ret;
}

/*
IntegerVectorList PolyhedralFan::getRaysInPrintingOrder(SymmetryGroup *sym)const
{
  assert(!cones.empty());
  int h=cones.begin()->dimensionOfLargestContainedSubspace();
  PolyhedralFan f=*this;
  while(f.getMaxDimension()!=h+1)
    {
      f=f.facetComplex();
    }

  IntegerVectorList rays;

  PolyhedralFan done(n);
  for(PolyhedralConeList::const_iterator i=f.cones.begin();i!=f.cones.end();i++)
    if(!done.contains(*i))
      for(SymmetryGroup::ElementContainer::const_iterator k=sym->elements.begin();k!=sym->elements.end();k++)
	{
	  PolyhedralCone cone=i->permuted(*k);
	  if(!done.contains(cone))
	    {
	      rays.push_back(cone.getRelativeInteriorPoint());
	      done.insert(cone);
	    }
	}
  return rays;
}
*/


IntegerVector PolyhedralFan::stableRay(PolyhedralCone const &c, SymmetryGroup const *sym)
{
  PolyhedralCone C=c;//cast away const instead?

  IntegerVector v=C.getRelativeInteriorPoint();

  IntegerVector ret(v.size());
  for(SymmetryGroup::ElementContainer::const_iterator k=sym->elements.begin();k!=sym->elements.end();k++)
    {
      IntegerVector v2=SymmetryGroup::compose(*k,v);
      if(c.contains(v2))ret+=v2;
    }
  return normalized(ret);
}


IntegerVector PolyhedralFan::stableRay(IntegerVector const &v, IntegerVectorList const &equations, IntegerVectorList const &inequalities, SymmetryGroup const *sym)
{
  IntegerVector ret(v.size());
  for(SymmetryGroup::ElementContainer::const_iterator k=sym->elements.begin();k!=sym->elements.end();k++)
    {
      IntegerVector v2=SymmetryGroup::compose(*k,v);
      bool containsV2=true;

      for(IntegerVectorList::const_iterator l=equations.begin();l!=equations.end();l++)
	if(dotLong(*l,v2)!=0)
	  {
	    containsV2=false;
	    goto leave;
	  }
      for(IntegerVectorList::const_iterator l=inequalities.begin();l!=inequalities.end();l++)
	if(dotLong(*l,v2)<0)
	  {
	    containsV2=false;
	    goto leave;
	  }
    leave:
      if(containsV2)ret+=v2;
    }
  return normalized(ret);
}

/* Slow version using facetComplexSymmetry()
IntegerVectorList PolyhedralFan::getRaysInPrintingOrder(SymmetryGroup *sym)const
{
  assert(!cones.empty());
  int h=cones.begin()->dimensionOfLinealitySpace();
  PolyhedralFan f=*this;
  if(f.getMaxDimension()==h)return IntegerVectorList();
  while(f.getMaxDimension()>h+1)
    {
      f=f.facetComplexSymmetry(*sym,true,true);
    }
  IntegerVectorList rays;

  for(PolyhedralConeList::const_iterator i=f.cones.begin();i!=f.cones.end();i++)
    {
      if(i->dimension()!=i->dimensionOfLinealitySpace())//This check is needed since the above while loop may not be run and therefore the lineality space may not have been removed.
	{
	  bool found=false;
	  for(IntegerVectorList::const_iterator j=rays.begin();j!=rays.end();j++)
	    if(i->contains(*j))found=true;

	  if(!found)
	    {
	      //IntegerVector interiorPointForOrbit=i->getRelativeInteriorPoint();
	      IntegerVector interiorPointForOrbit=stableRay(*i,sym);
	      PolyhedralFan done(n);
	      for(SymmetryGroup::ElementContainer::const_iterator k=sym->elements.begin();k!=sym->elements.end();k++)
		{
		  PolyhedralCone cone=i->permuted(*k);

		  if(!done.contains(cone))
		    {
		      rays.push_back(SymmetryGroup::compose(*k,interiorPointForOrbit));
		      done.insert(cone);
		    }
		}
	    }
	}
    }
  return rays;
  }*/

PolyhedralFan PolyhedralFan::rayComplexSymmetry(SymmetryGroup const &sym)const
{
  //  log0 fprintf(Stderr,"rayComplexSymmetry - begin\n");
  PolyhedralFan ret(n);
  log1 fprintf(Stderr,"Computing rays of %lu cones\n",cones.size());
  for(PolyhedralConeList::const_iterator i=cones.begin();i!=cones.end();i++)
    {
      {
	static int t;
	if(!((t++)%10))log1 fprintf(Stderr,"%i\n",t);
      }
      //  log0 fprintf(Stderr,"calling\n");
      IntegerVectorList rays=i->extremeRays();
      //log0 fprintf(Stderr,"returning\n");
      for(IntegerVectorList::const_iterator j=rays.begin();j!=rays.end();j++)
	{
	  bool alreadyInRet=false;
	  for(PolyhedralConeList::const_iterator I=ret.cones.begin();I!=ret.cones.end();I++)
	    for(SymmetryGroup::ElementContainer::const_iterator k=sym.elements.begin();k!=sym.elements.end();k++)
	      {
		IntegerVector u=SymmetryGroup::compose(*k,*j);
		if((I->contains(u)))
		  {
		    alreadyInRet=true;
		    goto exitLoop;
		  }
	      }
	exitLoop:
	  IntegerVectorList equations=i->getEquations();
	  IntegerVectorList inequalities1=i->getHalfSpaces();
	  IntegerVectorList inequalities2;
	  for(IntegerVectorList::const_iterator k=inequalities1.begin();k!=inequalities1.end();k++)
	    {
	      if(dotLong(*j,*k))
		inequalities2.push_back(*k);
	      else
		equations.push_back(*k);
	    }
	  PolyhedralCone C(inequalities2,equations,n);
	  C.canonicalize();
	  ret.insert(C);
	}
    }
  //  log0 fprintf(Stderr,"rayComplexSymmetry - end\n");
  return ret;
}


#if 0
IntegerVectorList PolyhedralFan::getRaysInPrintingOrder(SymmetryGroup const *sym)const
{
  assert(!cones.empty());
  int h=cones.begin()->dimensionOfLinealitySpace();

  /*
  PolyhedralFan f=*this;
  if(f.getMaxDimension()==h)return IntegerVectorList();
  while(f.getMaxDimension()>h+1)
    {
      f=f.facetComplexSymmetry(*sym,true,true);
    }
  */
  PolyhedralFan f=rayComplexSymmetry(*sym);
  IntegerVectorList rays;

  log1 fprintf(Stderr,"Number of cones in RayComplex: %i\n",f.cones.size());

  for(PolyhedralConeList::const_iterator i=f.cones.begin();i!=f.cones.end();i++)
    {
      static int t;
      log1 fprintf(Stderr,"%i\n",t++);
      if(i->dimension()!=i->dimensionOfLinealitySpace())//This check is needed since the above while loop may not be run and therefore the lineality space may not have been removed.
	{
	  bool found=false;
	  for(IntegerVectorList::const_iterator j=rays.begin();j!=rays.end();j++)
	    if(i->contains(*j))
	      {
		found=true;
		break;
	      }
	  if(!found)
	    {
	      //IntegerVector interiorPointForOrbit=i->getRelativeInteriorPoint();
	      IntegerVector interiorPointForOrbit=stableRay(*i,sym);
	      //    PolyhedralFan done(n);

	      //Check that this works:
	      set<IntegerVector> thisOrbitsRays;

	      for(SymmetryGroup::ElementContainer::const_iterator k=sym->elements.begin();k!=sym->elements.end();k++)
		{
		  IntegerVector temp=SymmetryGroup::compose(*k,interiorPointForOrbit);
		  thisOrbitsRays.insert(temp);
		}
	      for(set<IntegerVector>::const_iterator i=thisOrbitsRays.begin();i!=thisOrbitsRays.end();i++)rays.push_back(*i);
	      //Instead of this:
	      /*	      for(SymmetryGroup::ElementContainer::const_iterator k=sym->elements.begin();k!=sym->elements.end();k++)
		{
		  bool found=false;
		  IntegerVector temp=SymmetryGroup::compose(*k,interiorPointForOrbit);
		  for(IntegerVectorList::const_iterator j=rays.begin();j!=rays.end();j++)//REWRITE WITH LOGARITHMIC SEARCH
		    if(*j==temp)
		      {
			found=true;
			break;
		      }
		  if(!found)
		    {
		      PolyhedralCone cone=i->permuted(*k);
		      rays.push_back(SymmetryGroup::compose(*k,interiorPointForOrbit));
		      //      done.insert(cone);
		    }
		}
	      */
	    }
	}
    }
  return rays;
}

#elseif 0
//version used until Sep 2010
IntegerVectorList PolyhedralFan::getRaysInPrintingOrder(SymmetryGroup const *sym, bool upToSymmetry)const
{
	SymmetryGroup localsym(n);
	if(!sym)sym=&localsym;
  IntegerVectorList rays;
  log1 fprintf(Stderr,"Computing rays of %i cones\n",cones.size());
  for(PolyhedralConeList::const_iterator i=cones.begin();i!=cones.end();i++)
    {
      {
	static int t;
	if(!((t++)%10))log1 fprintf(Stderr,"%i\n",t);
      }
      IntegerVectorList temp=i->extremeRays();
      //      AsciiPrinter(Stderr).printVectorList(temp);

      for(IntegerVectorList::const_iterator j=temp.begin();j!=temp.end();j++)
	{
	  IntegerVectorList equations=i->getEquations();
	  IntegerVectorList inequalities1=i->getHalfSpaces();
	  IntegerVectorList inequalities2;
	  for(IntegerVectorList::const_iterator k=inequalities1.begin();k!=inequalities1.end();k++)
	    {
	      if(dotLong(*j,*k))
		inequalities2.push_back(*k);
	      else
		equations.push_back(*k);
	    }
	  bool isFound=false;
	  for(IntegerVectorList::const_iterator j2=rays.begin();j2!=rays.end();j2++)
	    for(SymmetryGroup::ElementContainer::const_iterator k=sym->elements.begin();k!=sym->elements.end();k++)
	      {
		bool isInCone=true;
		IntegerVector v=SymmetryGroup::compose(*k,*j2);
		for(IntegerVectorList::const_iterator l=equations.begin();l!=equations.end();l++)
		  if(dotLong(*l,v)!=0)
		    {
		      isInCone=false;
		      goto leave;
		    }
		for(IntegerVectorList::const_iterator l=inequalities2.begin();l!=inequalities2.end();l++)
		  if(dotLong(*l,v)<0)
		    {
		      isInCone=false;
		      goto leave;
		    }
	      leave:
		if(isInCone)
		  {
		    isFound=true;
		    goto leave2;
		  }
	      }
	leave2:
	  if(!isFound)
	    {
	      IntegerVector ray=stableRay(*j,equations,inequalities2,sym);
	      rays.push_back(ray);
	    }
	}
    }
  rays.sort();
  if(upToSymmetry)return rays;
  IntegerVectorList ret;
  for(IntegerVectorList::const_iterator i=rays.begin();i!=rays.end();i++)
    {
      set<IntegerVector> thisOrbitsRays;
      for(SymmetryGroup::ElementContainer::const_iterator k=sym->elements.begin();k!=sym->elements.end();k++)
	{
	  IntegerVector temp=SymmetryGroup::compose(*k,*i);
	  thisOrbitsRays.insert(temp);
	}
      for(set<IntegerVector>::const_iterator i=thisOrbitsRays.begin();i!=thisOrbitsRays.end();i++)ret.push_back(*i);
    }
  return ret;
}
#else
IntegerVectorList PolyhedralFan::getRaysInPrintingOrder(SymmetryGroup const *sym, bool upToSymmetry)const
{
  /*
   * The ordering changed in this version. Previously the orbit representatives stored in "rays" were
   * just the first extreme ray from the orbit that appeared. Now it is gotten using "orbitRepresentative"
   * which causes the ordering in which the different orbits appear to change.
   */

  if(cones.empty())return IntegerVectorList();
  IntegerVectorList generatorsOfLinealitySpace=cones.begin()->generatorsOfLinealitySpace();//all cones have the same lineality space

        SymmetryGroup localsym(n);
        if(!sym)sym=&localsym;
  set<IntegerVector> rays;
  log1 fprintf(Stderr,"Computing rays of %lu cones\n",cones.size());
  for(PolyhedralConeList::const_iterator i=cones.begin();i!=cones.end();i++)
    {
      {
        static int t;
        if(!((t++)%10))log1 fprintf(Stderr,"%i\n",t);
      }
      IntegerVectorList temp=i->extremeRays(&generatorsOfLinealitySpace);
      for(IntegerVectorList::const_iterator j=temp.begin();j!=temp.end();j++)
        rays.insert(sym->orbitRepresentative(*j));
    }
  IntegerVectorList ret;
  if(upToSymmetry)
    for(set<IntegerVector>::const_iterator i=rays.begin();i!=rays.end();i++)ret.push_back(*i);
  else
    for(set<IntegerVector>::const_iterator i=rays.begin();i!=rays.end();i++)
      {
        set<IntegerVector> thisOrbitsRays;
        for(SymmetryGroup::ElementContainer::const_iterator k=sym->elements.begin();k!=sym->elements.end();k++)
          {
            IntegerVector temp=SymmetryGroup::compose(*k,*i);
            thisOrbitsRays.insert(temp);
          }
        for(set<IntegerVector>::const_iterator i=thisOrbitsRays.begin();i!=thisOrbitsRays.end();i++)ret.push_back(*i);
      }
  return ret;
}


#endif


/*void PolyhedralFan::printWithIndices(class Printer *p, SymmetryGroup *sym)const //fan must be pure
{
  //  print(p);
  SymmetryGroup symm(n);
  if(!sym)sym=&symm;
  assert(!cones.empty());
  int h=cones.begin()->dimensionOfLargestContainedSubspace();
  fprintf(Stdout,"Rays:\n");
  //  IntegerVectorList rays;//=f.getRelativeInteriorPoints();
  fprintf(Stderr,"Computing rays...\n");
  IntegerVectorList rays=getRaysInPrintingOrder(sym);
  fprintf(Stderr,"Done computing rays.\n");
  p->printVectorList(rays,true);
  PolyhedralFan f=*this;

  //  while(f.getMaxDimension()>=h)
  IntegerVector fvector(f.getMaxDimension()-h);
  while(f.getMaxDimension()!=h)
    {
      int currentDimension=f.getMaxDimension()-h;
      fprintf(Stderr,"Processing dimension %i cones...\n",currentDimension);
      PolyhedralFan done(n);
      IntegerVector rayIncidenceCounter(rays.size());
      p->printString("Printing index list for dimension ");
      p->printInteger(currentDimension);
      p->printString(" cones:\n");
      p->printString("{\n");
      int faceIndex =0;
      bool split=false;
      bool addComma=false;
      for(PolyhedralConeList::const_iterator i=f.cones.begin();i!=f.cones.end();i++)
	{
	  if(!done.contains(*i))
	    {
	      for(SymmetryGroup::ElementContainer::const_iterator k=sym->elements.begin();k!=sym->elements.end();k++)
		{
		  PolyhedralCone cone=i->permuted(*k);
		  if(!done.contains(cone))
		    {
		      // p->printString("Face ");
		      // p->printInteger(faceIndex);
		      // p->printString(": ");
		      int rayIndex=0;
		      IntegerVector indices(0);
		      for(IntegerVectorList::const_iterator j=rays.begin();j!=rays.end();j++)
			{
			  if(cone.contains(*j))
			    {
			      indices.grow(indices.size()+1);
			      indices[indices.size()-1]=rayIndex;
			      rayIncidenceCounter[rayIndex]++;
			    }
			  rayIndex++;
			}
		      if(addComma)
			{
			  p->printString(",");
			  p->printNewLine();
			  if(split)
			    p->printNewLine();
			  split=false;
			}
		      p->printVector(indices,true);
		      addComma=true;
		      faceIndex++;
		      done.insert(cone);
		    }
		}
	      split=true;//p->printNewLine();
	    }
	}
      p->printString("}\n");
      p->printString("Number of dimension ");
      p->printInteger(f.getMaxDimension()-h);
      p->printString(" cones incident to each ray:\n");
      p->printVector(rayIncidenceCounter);
      p->printNewLine();
      fvector[f.getMaxDimension()-h-1]=faceIndex;
      f=f.facetComplex();
      fprintf(Stderr,"Done processing dimension %i cones.\n",currentDimension);
      //      fvector.grow(fvector.size()+1);fvector[fvector.size()-1]=faceIndex;
    }
  p->printString("F-vector:\n");
  p->printVector(fvector);
  p->printNewLine();
}
*/

 /*
void PolyhedralFan::printWithIndices(class Printer *p, SymmetryGroup *sym, const char *polymakeFileName)const //fan must be pure
{
  IntegerVector multiplicities;
  SymmetryGroup symm(n);
  PolymakeFile polymakeFile;






  if(polymakeFileName)
    {
      polymakeFile.create(polymakeFileName,"PolyhedralFan","PolyhedralFan");
    }

  if(!sym)sym=&symm;
  assert(!cones.empty());
  int h=cones.begin()->dimensionOfLinealitySpace();
  fprintf(Stdout,"Rays:\n");
  //  IntegerVectorList rays;//=f.getRelativeInteriorPoints();
  fprintf(Stderr,"Computing rays...\n");
  IntegerVectorList rays=getRaysInPrintingOrder(sym);
  fprintf(Stderr,"Done computing rays.\n");


  SymmetricComplex symCom(n,rays,*sym);


  if(p)
    p->printVectorList(rays,true);
  if(polymakeFileName)
    {
      polymakeFile.writeCardinalProperty("AMBIENT_DIM",n);
      polymakeFile.writeCardinalProperty("DIM",getMaxDimension());
      polymakeFile.writeCardinalProperty("LINEALITY_DIM",h);
      polymakeFile.writeMatrixProperty("RAYS",rowsToIntegerMatrix(rays,n));
      polymakeFile.writeCardinalProperty("N_RAYS",rays.size());
      polymakeFile.writeMatrixProperty("LINEALITY_SPACE",rowsToIntegerMatrix(highestDimensionalCone().linealitySpace().dualCone().getEquations()));
      polymakeFile.writeMatrixProperty("ORTH_LINEALITY_SPACE",rowsToIntegerMatrix(highestDimensionalCone().linealitySpace().getEquations()));
      polymakeFile.writeCardinalProperty("PURE",1);
    }


  PolyhedralFan f=*this;
  stringstream s;

  //  while(f.getMaxDimension()>=h)
  IntegerVector fvector(f.getMaxDimension()-h);
  bool isHighestDimension=true;
  while(f.getMaxDimension()!=h)
    {
      int currentDimension=f.getMaxDimension()-h;
      fprintf(Stderr,"Processing dimension %i cones...\n",currentDimension);
      IntegerVector rayIncidenceCounter(rays.size());
      if(p)
	{
	  p->printString("Printing index list for dimension ");
	  p->printInteger(currentDimension);
	  p->printString(" cones:\n");
	  p->printString("{\n");
	}
      int faceIndex =0;
      bool split=false;
      bool addComma=false;
      for(PolyhedralConeList::const_iterator i=f.cones.begin();i!=f.cones.end();i++)
	{
	  {
	    SymmetricComplex::Cone c;
	    c.dimension=i->dimension();

	    int rayIndex=0;
	    for(IntegerVectorList::const_iterator j=rays.begin();j!=rays.end();j++)
	      {
		if(i->contains(*j))c.insert(rayIndex);
		rayIndex++;
	      }
	    symCom.insert(c);
	  }


	  PolyhedralFan done(n);
	  for(SymmetryGroup::ElementContainer::const_iterator k=sym->elements.begin();k!=sym->elements.end();k++)
	    {
	      PolyhedralCone cone=i->permuted(*k);
	      if(!done.contains(cone))
		{
		  if(isHighestDimension)
		    {
		      multiplicities.grow(multiplicities.size()+1);
		      multiplicities[multiplicities.size()-1]=i->getMultiplicity();
		    }
		  // p->printString("Face ");
		  // p->printInteger(faceIndex);
		  // p->printString(": ");
		  int rayIndex=0;
		  IntegerVector indices(0);
		  for(IntegerVectorList::const_iterator j=rays.begin();j!=rays.end();j++)
		    {
		      if(cone.contains(*j))
			{
			  indices.grow(indices.size()+1);
			  indices[indices.size()-1]=rayIndex;
			  rayIncidenceCounter[rayIndex]++;
			}
		      rayIndex++;
		    }
		  if(addComma)
		    {
		      if(p)
			{
			  p->printString(",");
			  p->printNewLine();
			}
		      if(isHighestDimension)s<<endl;
		      if(split)
			{
			  if(p)p->printNewLine();
			  //	  s<<endl;
			}
		      split=false;
		    }
		  if(p)
		    p->printVector(indices,true);
		  if(isHighestDimension)
		    {
		      s << '{';
		      for(int i=0;i<indices.size();i++)
			{
			  if(i)s<<" ";
			  s<<indices[i];
			}
		      s << '}';
		    }
		  addComma=true;
		  faceIndex++;
		  done.insert(cone);
		}
	    }
	  split=true;//p->printNewLine();
	}
      if(p)
	{
	  p->printString("}\n");
	  p->printString("Number of dimension ");
	  p->printInteger(f.getMaxDimension()-h);
	  p->printString(" cones incident to each ray:\n");
	  p->printVector(rayIncidenceCounter);
	  p->printNewLine();
	}
      fvector[f.getMaxDimension()-h-1]=faceIndex;
      fprintf(Stderr,"TESTESTSETST\n");
      f=f.facetComplexSymmetry(*sym);
      fprintf(Stderr,"TESTESTSETST\n");
      fprintf(Stderr,"Done processing dimension %i cones.\n",currentDimension);
      //      fvector.grow(fvector.size()+1);fvector[fvector.size()-1]=faceIndex;
      isHighestDimension=false;
    }
  if(p)
    {
      p->printString("Multiplicities:\n");
      p->printVector(multiplicities);
      p->printNewLine();
      p->printString("F-vector:\n");
      p->printVector(fvector);
      p->printNewLine();
    }

  if(polymakeFileName)
    {
      polymakeFile.writeCardinalVectorProperty("F_VECTOR",fvector);
      s<<endl;
      polymakeFile.writeStringProperty("MAXIMAL_CONES",s.str());

      IntegerVectorList m;
      m.push_back(multiplicities);
      polymakeFile.writeMatrixProperty("MULTIPLICITIES",rowsToIntegerMatrix(m).transposed());
    }
  if(polymakeFileName)
    polymakeFile.close();


  AsciiPrinter(Stdout).printString(symCom.toString(symCom.getMinDim(),symCom.getMaxDim(),true,true));
}
*/



  /*MARKS CONES AS NONMAXIMAL IN THE SYMMETRIC COMPLEX IN WHICH THEY WILL BE INSERTED -not to be confused with the facet testing in the code
   */
 static list<SymmetricComplex::Cone> computeFacets(SymmetricComplex::Cone const &theCone, IntegerMatrix const &rays, IntegerVectorList const &facetCandidates, SymmetricComplex const &theComplex/*, int linealityDim*/)
{
  set<SymmetricComplex::Cone> ret;

  for(IntegerVectorList::const_iterator i=facetCandidates.begin();i!=facetCandidates.end();i++)
    {
      set<int> indices;

      bool notAll=false;
      for(vector<int>::const_iterator j=theCone.indices.begin();j!=theCone.indices.end();j++)
	if(dotLong(rays[*j],*i)==0)
	  indices.insert(*j);
	else
	  notAll=true;

      SymmetricComplex::Cone temp(indices,theCone.dimension-1,0,false,theComplex);
      /*      temp.multiplicity=0;
      temp.dimension=theCone.dimension-1;
      temp.setIgnoreSymmetry(true);
      */
      if(notAll)ret.insert(temp);

    }
  //  fprintf(Stderr,"HEJ!!!!\n");

  list<SymmetricComplex::Cone> ret2;
  for(set<SymmetricComplex::Cone>::const_iterator i=ret.begin();i!=ret.end();i++)
    {
      bool isMaximal=true;

      /*      if(i->indices.size()+linealityDim<i->dimension)//#3
	isMaximal=false;
	else*/
	for(set<SymmetricComplex::Cone>::const_iterator j=ret.begin();j!=ret.end();j++)
	  if(i!=j && i->isSubsetOf(*j))
	    {
	      isMaximal=false;
	      break;
	    }
      if(isMaximal)
	{
	  SymmetricComplex::Cone temp(i->indexSet(),i->dimension,i->multiplicity,true,theComplex);
	  temp.setKnownToBeNonMaximal(); // THIS IS WHERE WE SET THE CONES NON-MAXIMAL FLAG
	  //	  temp.setIgnoreSymmetry(false);
	  ret2.push_back(temp);
	}
    }
  return ret2;
}


void addFacesToSymmetricComplex(SymmetricComplex &c, PolyhedralCone const &cone, IntegerVectorList const &facetCandidates, IntegerVectorList const &generatorsOfLinealitySpace)
{
  IntegerMatrix const &rays=c.getVertices();
  set<int> indices;

//  for(int j=0;j<rays.getHeight();j++)if(cone.contains(rays[j]))indices.insert(j);

  IntegerVectorList l=cone.extremeRays(&generatorsOfLinealitySpace);
  for(IntegerVectorList::const_iterator i=l.begin();i!=l.end();i++)indices.insert(c.indexOfVertex(*i));

  addFacesToSymmetricComplex(c,indices,facetCandidates,cone.dimension(),cone.getMultiplicity());
}

void addFacesToSymmetricComplex(SymmetricComplex &c, set<int> const &indices, IntegerVectorList const &facetCandidates, int dimension, int multiplicity)
{
  IntegerMatrix const &rays=c.getVertices();
  list<SymmetricComplex::Cone> clist;
  {

    SymmetricComplex::Cone temp(indices,dimension,multiplicity,true,c);
    //    temp.dimension=cone.dimension();
    //   temp.multiplicity=cone.getMultiplicity();
    clist.push_back(temp);
  }

  //  int linealityDim=cone.dimensionOfLinealitySpace();

  while(!clist.empty())
    {
      SymmetricComplex::Cone &theCone=clist.front();

      if(!c.contains(theCone))
	{
	  log2
	  {
	    static int t;
	    if((t&1023)==0)
	      {
		fprintf(Stderr,"clist size:%lu\n",clist.size());
	      }
	    t++;
	  }

	  c.insert(theCone);
	  //	  log0 fprintf(Stderr,"ADDING\n");
	  list<SymmetricComplex::Cone> facets=computeFacets(theCone,rays,facetCandidates,c/*,linealityDim*/);
	  clist.splice(clist.end(),facets);
	}
      clist.pop_front();
    }

}


/**
   Produce strings that express the vectors in terms of rays of the fan modulo the lineality space. Symmetry is ignored??
 */
vector<string> PolyhedralFan::renamingStrings(IntegerVectorList const &theVectors, IntegerVectorList const &originalRays, IntegerVectorList const &linealitySpace, SymmetryGroup *sym)const
{
  vector<string> ret;
  for(IntegerVectorList::const_iterator i=theVectors.begin();i!=theVectors.end();i++)
    {
      for(PolyhedralConeList::const_iterator j=cones.begin();j!=cones.end();j++)
	{
	  if(j->contains(*i))
	    {
	      vector<int> relevantIndices;
	      IntegerVectorList relevantRays=linealitySpace;
	      int K=0;
	      for(IntegerVectorList::const_iterator k=originalRays.begin();k!=originalRays.end();k++,K++)
		if(j->contains(*k))
		  {
		    relevantIndices.push_back(K);
		    relevantRays.push_back(*k);
		  }

	      FieldMatrix LFA(Q,relevantRays.size(),n);
	      int J=0;
	      for(IntegerVectorList::const_iterator j=relevantRays.begin();j!=relevantRays.end();j++,J++)
		LFA[J]=integerVectorToFieldVector(*j,Q);
	      FieldVector LFB=concatenation(integerVectorToFieldVector(*i,Q),FieldVector(Q,relevantRays.size()));
	      LFA=LFA.transposed();
	      FieldVector LFX=LFA.solver().canonicalize(LFB);
	      stringstream s;
	      if(LFX.subvector(0,n).isZero())
	        {
		  s<<"Was:";
	          FieldVector S=LFX.subvector(n+linealitySpace.size(),LFX.size());
		  for(int k=0;k<S.size();k++)
		    if(!S[k].isZero())
		      s<<"+"<<S[k].toString()<<"*["<<relevantIndices[k]<<"] ";
	        }
	      ret.push_back(s.str());
	      break;
	    }
	}
    }
  return ret;
}

SymmetricComplex PolyhedralFan::toSymmetricComplex(SymmetryGroup *sym)
{
  SymmetryGroup symm(n);
	  if(!sym)sym=&symm;

	  IntegerVectorList rays=getRaysInPrintingOrder(sym);

	  SymmetricComplex symCom(n,rays,*sym);

	  if(cones.empty())return symCom;
	  IntegerVectorList generatorsOfLinealitySpace=cones.begin()->generatorsOfLinealitySpace();

	  for(PolyhedralConeList::const_iterator i=cones.begin();i!=cones.end();i++)
	    {
	      {
		static int t;
		log1 fprintf(Stderr,"Adding faces of cone %i\n",t++);
	      }
	      log2 fprintf(Stderr,"Dim: %i\n",i->dimension());

	      addFacesToSymmetricComplex(symCom,*i,i->getHalfSpaces(),generatorsOfLinealitySpace);
	    }

	  log1 cerr<<"Remapping";
	  symCom.remap();
	  log1 cerr<<"Done remapping";
	  return symCom;
}

void PolyhedralFan::printWithIndices(class Printer *p, int flags, SymmetryGroup *sym, vector<string> const *comments)const
//void PolyhedralFan::printWithIndices(class Printer *p, bool printMultiplicities, SymmetryGroup *sym, bool group, bool ignoreCones, bool xml, bool tPlaneSort, vector<string> const *comments)const
{
  assert(p);
  //  IntegerVector multiplicities;
  SymmetryGroup symm(n);

  PolymakeFile polymakeFile;
//  polymakeFile.create("NONAME","fan","PolyhedralFan",flags&FPF_xml);
  polymakeFile.create("NONAME","fan","SymmetricFan",flags&FPF_xml);

  bool produceXml=polymakeFile.isXmlFormat();


  if(!sym)sym=&symm;

  if(cones.empty())
    {
      p->printString("Polyhedral fan is empty. Printing not supported.\n");
      return;
    }

  int h=cones.begin()->dimensionOfLinealitySpace();

  log1 fprintf(Stderr,"Computing rays.\n");
  IntegerVectorList rays=getRaysInPrintingOrder(sym);

  SymmetricComplex symCom(n,rays,*sym);

  polymakeFile.writeCardinalProperty("AMBIENT_DIM",n);
  polymakeFile.writeCardinalProperty("DIM",getMaxDimension());
  polymakeFile.writeCardinalProperty("LINEALITY_DIM",h);
  polymakeFile.writeMatrixProperty("RAYS",rowsToIntegerMatrix(rays,n),true,comments);
  polymakeFile.writeCardinalProperty("N_RAYS",rays.size());
  IntegerVectorList linealitySpaceGenerators=highestDimensionalCone().linealitySpace().dualCone().getEquations();
  polymakeFile.writeMatrixProperty("LINEALITY_SPACE",rowsToIntegerMatrix(linealitySpaceGenerators,n));
  polymakeFile.writeMatrixProperty("ORTH_LINEALITY_SPACE",rowsToIntegerMatrix(highestDimensionalCone().linealitySpace().getEquations(),n));

  if(flags & FPF_primitiveRays)
  {
	 IntegerVectorList primitiveRays;
	 for(IntegerVectorList::const_iterator i=rays.begin();i!=rays.end();i++)
		 for(PolyhedralConeList::const_iterator j=cones.begin();j!=cones.end();j++)
			 if(j->contains(*i)&&(j->dimensionOfLinealitySpace()+1==j->dimension()))
					 primitiveRays.push_back(j->semiGroupGeneratorOfRay());

	  polymakeFile.writeMatrixProperty("PRIMITIVE_RAYS",rowsToIntegerMatrix(primitiveRays,n));
  }


  IntegerVectorList generatorsOfLinealitySpace=cones.begin()->generatorsOfLinealitySpace();

  log1 fprintf(Stderr,"Building symmetric complex.\n");
  for(PolyhedralConeList::const_iterator i=cones.begin();i!=cones.end();i++)
    {
      {
	static int t;
	log1 fprintf(Stderr,"Adding faces of cone %i\n",t++);
      }
      log2 fprintf(Stderr,"Dim: %i\n",i->dimension());

      addFacesToSymmetricComplex(symCom,*i,i->getHalfSpaces(),generatorsOfLinealitySpace);
    }

  log1 cerr<<"Remapping";
  symCom.remap();
  log1 cerr<<"Done remapping";


  PolyhedralFan f=*this;

  //  IntegerVector fvector(f.getMaxDimension()-h);



  //fprintf(Stderr,"maxdim %i h %i\n",f.getMaxDimension(),h);
  /*  while(!f.cones.empty())
    {
      int currentDimension=f.getMaxDimension()-h;
      IntegerVector rayIncidenceCounter(rays.size());
      int faceIndex =0;
      bool split=false;
      bool addComma=false;
      for(PolyhedralConeList::const_iterator i=f.cones.begin();i!=f.cones.end();i++)
	{
	  {
	    SymmetricComplex::Cone c;
	    c.dimension=i->dimension();
	    c.multiplicity=i->getMultiplicity();

	    int rayIndex=0;
	    for(IntegerVectorList::const_iterator j=rays.begin();j!=rays.end();j++)
	      {
		if(i->contains(*j))c.insert(rayIndex);
		rayIndex++;
	      }
	    symCom.insert(c);
	  }
	}
      //      fvector[f.getMaxDimension()-h-1]=faceIndex;
      f=f.facetComplexSymmetry(*sym);
    }
  */
  log1 fprintf(Stderr,"Computing f-vector.\n");
  IntegerVector fvector=symCom.fvector();
  polymakeFile.writeCardinalVectorProperty("F_VECTOR",fvector);
  log1 fprintf(Stderr,"Done computing f-vector.\n");

  if(flags&FPF_boundedInfo)
    {
      log1 fprintf(Stderr,"Computing bounded f-vector.\n");
      IntegerVector fvectorBounded=symCom.fvector(true);
      polymakeFile.writeCardinalVectorProperty("F_VECTOR_BOUNDED",fvectorBounded);
      log1 fprintf(Stderr,"Done computing bounded f-vector.\n");
    }
/*
 * Removed to make the Polymake people happy.
 *    {
    int euler=0;
    int mul=-1;
    for(int i=0;i<fvector.size();i++,mul*=-1)euler+=mul*fvector[i];
    polymakeFile.writeCardinalProperty("MY_EULER",euler);
  }
*/
  log1 fprintf(Stderr,"Checking if complex is simplicial and pure.\n");
  polymakeFile.writeBooleanProperty("SIMPLICIAL",symCom.isSimplicial());
  polymakeFile.writeBooleanProperty("PURE",symCom.isPure());
  log1 fprintf(Stderr,"Done checking.\n");


  if(flags&FPF_conesCompressed)
  {
    polymakeFile.writeArrayArrayIntProperty("SYMMETRY_GENERATORS",rowsToIntegerMatrix(sym->getUniqueGenerators(),n));
    log1 fprintf(Stderr,"Producing list of cones up to symmetry.\n");
    polymakeFile.writeStringProperty("CONES_ORBITS",symCom.toString(symCom.getMinDim(),symCom.getMaxDim(),false,flags&FPF_group,0,true,flags&FPF_tPlaneSort,produceXml));
    log1 fprintf(Stderr,"Done producing list of cones up to symmetry.\n");
    log1 fprintf(Stderr,"Producing list of maximal cones up to symmetry.\n");
    stringstream multiplicities;
    polymakeFile.writeStringProperty("MAXIMAL_CONES_ORBITS",symCom.toString(symCom.getMinDim(),symCom.getMaxDim(),true,flags&FPF_group, &multiplicities,true,flags&FPF_tPlaneSort,produceXml));
    if(flags&FPF_multiplicities)polymakeFile.writeStringProperty("MULTIPLICITIES_ORBITS",multiplicities.str());
    log1 fprintf(Stderr,"Done producing list of maximal cones up to symmetry.\n");
  }

  if(flags&FPF_conesExpanded)
    {
      if(flags&FPF_cones)
	{
	  log1 fprintf(Stderr,"Producing list of cones.\n");
	  polymakeFile.writeStringProperty("CONES",symCom.toString(symCom.getMinDim(),symCom.getMaxDim(),false,flags&FPF_group,0,false,flags&FPF_tPlaneSort,produceXml));
	  log1 fprintf(Stderr,"Done producing list of cones.\n");
	}
      if(flags&FPF_maximalCones)
	{
	  log1 fprintf(Stderr,"Producing list of maximal cones.\n");
	  stringstream multiplicities;
	  polymakeFile.writeStringProperty("MAXIMAL_CONES",symCom.toString(symCom.getMinDim(),symCom.getMaxDim(),true,flags&FPF_group, &multiplicities,false,flags&FPF_tPlaneSort,produceXml));
	  if(flags&FPF_multiplicities)polymakeFile.writeStringProperty("MULTIPLICITIES",multiplicities.str());
	  log1 fprintf(Stderr,"Done producing list of maximal cones.\n");
	}
    }

  if(flags&FPF_values)
    {
      {
	IntegerVectorList values;
	for(IntegerVectorList::const_iterator i=linealitySpaceGenerators.begin();i!=linealitySpaceGenerators.end();i++)
	  {
	    IntegerVector v(1);
	    v[0]=evaluatePiecewiseLinearFunction(*i);
	    values.push_back(v);
	  }
	polymakeFile.writeMatrixProperty("LINEALITY_VALUES",rowsToIntegerMatrix(values,1));
      }
      {
	IntegerVectorList values;
	for(IntegerVectorList::const_iterator i=rays.begin();i!=rays.end();i++)
	  {
	    IntegerVector v(1);
	    v[0]=evaluatePiecewiseLinearFunction(*i);
	    values.push_back(v);
	  }
	polymakeFile.writeMatrixProperty("RAY_VALUES",rowsToIntegerMatrix(values,1));
      }
    }


  log1 fprintf(Stderr,"Producing final string for output.\n");
  stringstream s;
  polymakeFile.writeStream(s);
  string S=s.str();
  log1 fprintf(Stderr,"Printing string.\n");
  p->printString(S.c_str());
  log1 fprintf(Stderr,"Done printing string.\n");
}


PolyhedralFan PolyhedralFan::readFan(string const &filename, bool onlyMaximal, IntegerVector *w, set<int> const *coneIndices, SymmetryGroup const *sym, bool readCompressedIfNotSym)
{
    PolymakeFile inFile;
    inFile.open(filename.c_str());

    int n=inFile.readCardinalProperty("AMBIENT_DIM");
    int nRays=inFile.readCardinalProperty("N_RAYS");
    IntegerMatrix rays=inFile.readMatrixProperty("RAYS",nRays,n);
    int linealityDim=inFile.readCardinalProperty("LINEALITY_DIM");
    IntegerMatrix linealitySpace=inFile.readMatrixProperty("LINEALITY_SPACE",linealityDim,n);


    const char *sectionName=0;
    const char *sectionNameMultiplicities=0;
    if(sym || readCompressedIfNotSym)
    {
      sectionName=(onlyMaximal)?"MAXIMAL_CONES_ORBITS":"CONES_ORBITS";
      sectionNameMultiplicities=(onlyMaximal)?"MULTIPLICITIES_ORBITS":"DUMMY123";
    }
      else
      {  sectionName=(onlyMaximal)?"MAXIMAL_CONES":"CONES";
      sectionNameMultiplicities=(onlyMaximal)?"MULTIPLICITIES":"DUMMY123";
      }


    IntegerVector w2(n);
    if(w==0)w=&w2;

    SymmetryGroup sym2(n);
    if(sym==0)sym=&sym2;

    vector<list<int> > cones=inFile.readMatrixIncidenceProperty(sectionName);
    IntegerVectorList r;

    bool hasMultiplicities=inFile.hasProperty(sectionNameMultiplicities);
    IntegerMatrix multiplicities(0,0);
    if(hasMultiplicities)multiplicities=inFile.readMatrixProperty(sectionNameMultiplicities,cones.size(),1);


    PolyhedralFan ret(n);

    log2 cerr<< "Number of orbits to expand "<<cones.size()<<endl;
    for(int i=0;i<cones.size();i++)
      if(coneIndices==0 || coneIndices->count(i))
	{
	  log2 cerr<<"Expanding symmetries of cone"<<endl;
	  /*	  for(SymmetryGroup::ElementContainer::const_iterator perm=sym->elements.begin();perm!=sym->elements.end();perm++)
	    {
	      IntegerVectorList coneRays;
	      for(list<int>::const_iterator j=cones[i].begin();j!=cones[i].end();j++)
		coneRays.push_back(SymmetryGroup::compose(*perm,rays[*j]));
	      if(isInNonNegativeSpan(*w,coneRays,linealitySpace.getRows()))
		{
		  PolyhedralCone C=PolyhedralCone::givenByRays(coneRays,linealitySpace.getRows(),n);
		  C.canonicalize();
		  ret.insert(C);
		}
	    }
	  */
	  {
	    IntegerVectorList coneRays;
	    for(list<int>::const_iterator j=cones[i].begin();j!=cones[i].end();j++)
	      coneRays.push_back((rays[*j]));
	    PolyhedralCone C=PolyhedralCone::givenByRays(coneRays,linealitySpace.getRows(),n);
	    if(hasMultiplicities)C.setMultiplicity(multiplicities[i][0]);
	    for(SymmetryGroup::ElementContainer::const_iterator perm=sym->elements.begin();perm!=sym->elements.end();perm++)
	      {
		if(C.contains(SymmetryGroup::composeInverse(*perm,*w)))
		  {
		    PolyhedralCone C2=C.permuted(*perm);
		    C2.canonicalize();
		    ret.insert(C2);
		  }
	      }
	  }
	}
    return ret;
}


IncidenceList PolyhedralFan::getIncidenceList(SymmetryGroup *sym)const //fan must be pure
{
  IncidenceList ret;
  SymmetryGroup symm(n);
  if(!sym)sym=&symm;
  assert(!cones.empty());
  int h=cones.begin()->dimensionOfLinealitySpace();
  IntegerVectorList rays=getRaysInPrintingOrder(sym);
  PolyhedralFan f=*this;

  while(f.getMaxDimension()!=h)
    {
      IntegerVectorList l;
      PolyhedralFan done(n);
      IntegerVector rayIncidenceCounter(rays.size());
      int faceIndex =0;
      for(PolyhedralConeList::const_iterator i=f.cones.begin();i!=f.cones.end();i++)
	{
	  if(!done.contains(*i))
	    {
	      for(SymmetryGroup::ElementContainer::const_iterator k=sym->elements.begin();k!=sym->elements.end();k++)
		{
		  PolyhedralCone cone=i->permuted(*k);
		  if(!done.contains(cone))
		    {
		      int rayIndex=0;
		      IntegerVector indices(0);
		      for(IntegerVectorList::const_iterator j=rays.begin();j!=rays.end();j++)
			{
			  if(cone.contains(*j))
			    {
			      indices.grow(indices.size()+1);
			      indices[indices.size()-1]=rayIndex;
			      rayIncidenceCounter[rayIndex]++;
			    }
			  rayIndex++;
			}
		      l.push_back(indices);
		      faceIndex++;
		      done.insert(cone);
		    }
		}
	    }
	}
      ret[f.getMaxDimension()]=l;
      f=f.facetComplex();
    }
  return ret;
}


void PolyhedralFan::makePure()
{
  if(getMaxDimension()!=getMinDimension())removeAllLowerDimensional();
}

bool PolyhedralFan::contains(PolyhedralCone const &c)const
{
  return cones.count(c);
}


PolyhedralCone PolyhedralFan::coneContaining(IntegerVector const &v)const
{
  for(PolyhedralConeList::const_iterator i=cones.begin();i!=cones.end();i++)
    if(i->contains(v))return i->faceContaining(v);
  debug<<"Vector "<<v<<" not contained in support of fan\n";
  assert(0);
}


PolyhedralFan::coneIterator PolyhedralFan::conesBegin()const
{
  return cones.begin();
}


PolyhedralFan::coneIterator PolyhedralFan::conesEnd()const
{
  return cones.end();
}


bool PolyhedralFan::isRefinementOf(PolyhedralFan const &f)const
{
  /*  for(PolyhedralConeList::const_iterator i=cones.begin();i!=cones.end();i++)
    {
      static int t;
      fprintf(Stderr,"%i\n",t++);
      for(PolyhedralConeList::const_iterator j=f.cones.begin();j!=f.cones.end();j++)
	{
	  PolyhedralCone c=intersection(*i,*j);
	  if(c.dimension()==n)
	    {

	      if(!j->contains(*i))
		return false;
	    }
	}
	}*/

  int t=0;
  for(PolyhedralConeList::const_iterator j=f.cones.begin();j!=f.cones.end();j++)
    {
      int t1=0;
      for(PolyhedralConeList::const_iterator i=cones.begin();i!=cones.end();i++)
	{
	  PolyhedralCone c=intersection(*i,*j);
	  if(c.dimension()==n)
	    {
	      t1++;
	      if(!j->contains(*i))
		return false;
	    }
	}
      fprintf(Stderr,"%i\n",t1);
      t+=t1;
    }
  fprintf(Stderr,"%i\n",t);

      /*      bool found=false;
      for(PolyhedralConeList::const_iterator j=f.cones.begin();j!=f.cones.end();j++)
	  if(j->contains(*i)){
	    found=true;
	    break;
	  }
      if(!found)
	{
	  for(PolyhedralConeList::const_iterator j=f.cones.begin();j!=f.cones.end();j++)
	    {
	      PolyhedralCone c=intersection(*i,*j);
	      if(c.dimension()==n){
		AsciiPrinter(Stderr).printVector(c.getRelativeInteriorPoint());
	      }
	    }

	  return false;
	  }*/

  return true;
}

/*	    for(SymmetryGroup::ElementContainer::const_iterator perm=sym->elements.begin();perm!=sym->elements.end();perm++)
	      {
		if(C.contains(SymmetryGroup::composeInverse(*perm,*w)))
		  {
		    PolyhedralCone C2=C.permuted(*perm);
		    C2.canonicalize();
		    ret.insert(C2);
		  }
	      }
*/
PolyhedralFan PolyhedralFan::link(IntegerVector const &w, SymmetryGroup *sym)const
{
  SymmetryGroup symL(n);
  if(!sym)sym=&symL;

  PolyhedralFan ret(n);

  for(PolyhedralConeList::const_iterator i=cones.begin();i!=cones.end();i++)
    {
      for(SymmetryGroup::ElementContainer::const_iterator perm=sym->elements.begin();perm!=sym->elements.end();perm++)
	{
	  IntegerVector w2=SymmetryGroup::composeInverse(*perm,w);
	  if(i->contains(w2))
	    {
	      IntegerVectorList equations=i->getEquations();
	      IntegerVectorList inequalities1=i->getHalfSpaces();
	      IntegerVectorList inequalities2;
	      for(IntegerVectorList::const_iterator j=inequalities1.begin();j!=inequalities1.end();j++)
		if(dotLong(w2,*j)==0)inequalities2.push_back(*j);
	      PolyhedralCone C(inequalities2,equations,n);
	      C.canonicalize();
	      C.setLinearForm(i->getLinearForm());
	      PolyhedralCone C2=C.permuted(*perm);
	      C2.canonicalize();
	      C2.setMultiplicity(i->getMultiplicity());
	      ret.insert(C2);
	    }
	}
    }
  return ret;
}

PolyhedralFan PolyhedralFan::link(IntegerVector const &w)const
{
  PolyhedralFan ret(n);

  for(PolyhedralConeList::const_iterator i=cones.begin();i!=cones.end();i++)
    {
      if(i->contains(w))
	{
	  IntegerVectorList equations=i->getEquations();
	  IntegerVectorList inequalities1=i->getHalfSpaces();
	  IntegerVectorList inequalities2;
	  for(IntegerVectorList::const_iterator j=inequalities1.begin();j!=inequalities1.end();j++)
	    if(dotLong(w,*j)==0)inequalities2.push_back(*j);
	  PolyhedralCone C(inequalities2,equations,n);
	  C.canonicalize();
	  C.setLinearForm(i->getLinearForm());
      C.setMultiplicity(i->getMultiplicity());
	  ret.insert(C);
	}
    }
  return ret;
}


int64 PolyhedralFan::evaluatePiecewiseLinearFunction(IntegerVector const &x)const
{
  for(PolyhedralConeList::const_iterator i=cones.begin();i!=cones.end();i++)
    {
      if(i->contains(x))return dotLong(i->getLinearForm(),x);
    }
  assert(0);
  return 0;
}


FieldElement PolyhedralFan::volume(int d, SymmetryGroup *sym)const
{
  SymmetryGroup symL(n);
  if(!sym)sym=&symL;

  FieldElement ret(Q);

  for(PolyhedralConeList::const_iterator i=cones.begin();i!=cones.end();i++)
    {
      if(i->dimension()==d)
	{
	  IntegerVector w=stableRay(*i,sym);
	  ret=ret+Q.zHomomorphism(sym->orbitSize(w))*i->volume();
	}
    }
  return ret;
}


bool PolyhedralFan::isConnected(SymmetryGroup *sym)const
{
  SymmetryGroup symL(n);
  if(!sym)sym=&symL;

  CodimOneConnectednessTester ct;

  for(PolyhedralConeList::const_iterator i=cones.begin();i!=cones.end();i++)
    {
      log2 cerr<<"Computing ridges of facet." << endl;
      PolyhedralFan ridges=facetsOfCone(*i);
      IntegerVectorList interiorPoints;
      for(PolyhedralConeList::const_iterator j=ridges.cones.begin();j!=ridges.cones.end();j++)
	interiorPoints.push_back(sym->orbitRepresentative(j->getUniquePoint()));
      ct.insertFacetOrbit(interiorPoints);
    }
  return ct.isConnected();
}


int PolyhedralFan::size()const
{
  return cones.size();
}

int PolyhedralFan::dimensionOfLinealitySpace()const
{
  assert(cones.size());//slow!
  return cones.begin()->dimensionOfLinealitySpace();
}

PolyhedralFan PolyhedralFan::negated()const
{
  PolyhedralFan ret(n);

  for(coneIterator i=conesBegin();i!=conesEnd();i++)
    ret.insert(i->negated());
  return ret;
}


bool PolyhedralFan::isCompatible(PolyhedralCone const &c)const
{
  for(PolyhedralConeList::const_iterator i=cones.begin();i!=cones.end();i++)
    {
      PolyhedralCone C=intersection(c,*i);
      C.canonicalize();
      if(!c.hasFace(C))return false;
      if(!i->hasFace(C))return false;
    }
  return true;
}

void PolyhedralFan::merge(PolyhedralCone const &c)
{
  AsciiPrinter P(Stderr);

  if(isCompatible(c))insert(c);
  else
    {
      assert(0);//Does not work in general.
    }
  /*
  //  P<<"BEFORE MERGE-------------------------" <<*this;

  PolyhedralFan ret=complementOfCone(c,false);
  //  P<<"COMPLEMENT OF CONE-------------------------" <<ret;
  ret=refinement(*this,ret);

  PolyhedralFan C(c.ambientDimension());
  C.insert(c);

  for(PolyhedralConeList::const_iterator i=cones.begin();i!=cones.end();i++)
    C=refinement(complementOfCone(*i,true),C);

  for(PolyhedralConeList::const_iterator i=C.cones.begin();i!=C.cones.end();i++)
    ret.insert(*i);
  *this=ret;

  // P<<"AFTER MERGE" <<*this;
  */
}



void PolyhedralFan::removeNonMaximal()
{
  for(PolyhedralConeList::iterator i=cones.begin();i!=cones.end();)
    {
      IntegerVector w=i->getRelativeInteriorPoint();
      bool containedInOther=false;
      for(PolyhedralConeList::iterator j=cones.begin();j!=cones.end();j++)
	if(j!=i)
	  {
	    if(j->contains(w)){containedInOther=true;break;}
	  }
      if(containedInOther)
	{
	  PolyhedralConeList::iterator k=i;
	  i++;
	  cones.erase(k);
	}
      else i++;
    }
}