File: Binomials.m2

package info (click to toggle)
macaulay2 1.21%2Bds-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 133,096 kB
  • sloc: cpp: 110,377; ansic: 16,306; javascript: 4,193; makefile: 3,821; sh: 3,580; lisp: 764; yacc: 590; xml: 177; python: 140; perl: 114; lex: 65; awk: 3
file content (2015 lines) | stat: -rw-r--r-- 74,867 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
-- -*- coding: utf-8 -*-
--  Binomials.m2
--
--  Copyright (C) 2009-2014 Thomas Kahle <thomas.kahle@jpberlin.de>
--
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
--
--  This program is free software; you can redistribute it and/or modify
--  it under the terms of the GNU General Public License as published by
--  the Free Software Foundation; either version 2 of the License, or (at
--  your option) any later version.
--
--  This program is distributed in the hope that it will be useful, but
--  WITHOUT ANY WARRANTY; without even the implied warranty of
--  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
--  General Public License for more details.
--
--  You should have received a copy of the GNU General Public License along
--  with this program; if not, write to the Free Software Foundation, Inc.,
--  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
--
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

newPackage(
	"Binomials",
	Version => "1.2.1",
	Date => "January 2018",
	Authors => {{
		  Name => "Thomas Kahle",
		  Email => "thomas.kahle@jpberlin.de",
		  HomePage => "http://www.thomas-kahle.de"}},
    	Headline => "specialized routines for binomial ideals",
	Keywords => {"Commutative Algebra"},
	PackageImports => {"FourTiTwo", "Cyclotomic", "LLLBases", "MinimalPrimes", "Elimination"},
	Certification => {
	     "journal name" => "The Journal of Software for Algebra and Geometry: Macaulay2",
	     "journal URI" => "http://j-sag.org/",
	     "article title" => "Decompositions of binomial ideals",
	     "acceptance date" => "2012-02-06",
	     "published article URI" => "http://j-sag.org/Volume4/jsag-1-2012.pdf",
	     "published code URI" => "http://j-sag.org/Volume4/Binomials.m2",
	     "repository code URI" => "https://github.com/Macaulay2/M2/blob/master/M2/Macaulay2/packages/Binomials.m2",
	     "release at publication" => "6c927c4f11724e29840c889e5ac7a426b17685ab",
	     "version at publication" => "1.0",
	     "volume number" => "4",
	     "volume URI" => "http://j-sag.org/Volume4/"
	     }
    	)
   
export {
     -- 'Official' functions
     "binomialPrimaryDecomposition",
     "binomialCellularDecomposition",
     "binomialUnmixedDecomposition",
     "binomialRadical",
     "binomialMinimalPrimes",
     "binomialAssociatedPrimes",
     "binomialSolve",
     -- tests
     "binomialIsPrime",
     "binomialIsPrimary",
     "cellularBinomialIsPrimary",
     "isCellular",
     "isBinomial",
     "isUnital",
     -- input related
     "makeBinomial",
     "latticeBasisIdeal",
     -- cellular stuff:
     "cellularBinomialAssociatedPrimes",
     "cellularBinomialUnmixedDecomposition",
     -- "cellularAssociatedLattices",
     "cellularBinomialPrimaryDecomposition",
     "cellularBinomialRadical",
     -- simple wrappers:
     "BPD",
     "BCD",
     "BUD",
     -- auxiliary functions:
     "partialCharacter",
     "idealFromCharacter",  -- should be renamed to ideal once M2 supports this
     "randomBinomialIdeal",
     "extractInclusionMinimalIdeals",
     -- Not in the interface:
--     "axisSaturate",
--     "cellVars",
--     "cellularEmbeddedLatticeWitnesses",
--     "Lsat",
--     "saturatePChar",
--     "satIdeals",
--     "nonCellstdm",
--     "maxNonCellstdm",
--     "minimalPrimaryComponent",
--     "binomialFrobeniusPower",

     -- Options
     "CellVariables", -- for partialCharacter
     "ReturnPrimes", -- for cellularBinomialIsPrimary 
     "ReturnPChars", -- for cellularBinomialIsPrimary
     "ReturnCellVars", -- for binomialCellularDecomposition
     
     --Types
     "PartialCharacter"--HashTable
     }

axisSaturate = (I,i) -> (
-- By Ignacio Ojeda and Mike Stillman
-- For computing saturations w.r.t. a single variable:
    R := ring I;
    I1 := ideal(1_R);
    s := 0;
    f := R_i;
    while not(I1 == I) do (
	s = s + 1;
	I1 = I;
	I = ideal syz gb(matrix{{f}}|gens I,
            SyzygyRows=>1,Syzygies=>true););
    {s-1, I}
    )

-- Cellular decomposition of binomial ideals:
binomialCellularDecomposition = method (Options => {ReturnCellVars => false, Verbose=>false})
binomialCellularDecomposition Ideal := Ideal => o -> I -> (
-- based on code by Ignacio Ojeda and Mike Stillman     
     R := ring I;
     if I == ideal (1_R) then return {};
     n := numgens R;
     Answer := {};
     L := null;
     IntersectAnswer := ideal(1_R);
     ToDo := {{{1_R},toList(0..n-1),I}};
     -- Each entry of the ToDoList is a triple:
     -- #0 contains list of variables with respect to which is already saturated
     -- #1 contains variables to be considered for cell variables
     -- #2 is the ideal to decompose
     compo := 0;
     next := () -> (
	 if #ToDo === 0 then false
	 else (
	      L = ToDo#0;
	      ToDo = drop(ToDo,1);
	      if gens IntersectAnswer % L#2 == 0 then (
		   if o#Verbose then (
			<< "redundant component" << endl;
			)
		   )
	      -- if its not redundant:
	      else if #(L#1) === 0 then ( -- #(L#1) counts 'remaining variables to check'
		   -- no variables remain to check :
		   -- We have an answer
                   compo = compo + 1; 
		   newone := trim L#2;
		   if o#Verbose then (
			<< "cellular components found: " << compo << endl;);
		   if o#ReturnCellVars then Answer = append(Answer,{newone, delete(1_R,L#0)})
		   else Answer = append (Answer,newone);
		   IntersectAnswer = intersect(IntersectAnswer,newone);
		   -- if we have enough, stop after this iteration
		   if IntersectAnswer == I then ToDo = {})
	      else ( -- So, there are remaining variables #(L#1) is not zero
	           i := L#1#0; -- i is a variable under consideration
		   newL1 := drop(L#1,1); -- gets removed from the list
	           result := axisSaturate(L#2, i); -- compute saturation wrt i
		   J := result#1; -- Ideal
		   k := result#0; -- Saturation Exponent
		   if k > 0 then ( -- If a division was needed:
     	       	    	-- We add the monomial i^k to ideal under consideration		      	   	
			J2 := L#2 + ideal(R_i^k); 
     	       	    	-- And remove L#0 components from variables that we already
			-- considered before
			J2 = saturate(J2, product L#0);
			if J2 != ideal(1_R) then
			    -- If something is left after removing we have more to decompose J2
			    ToDo = prepend({L#0, newL1, J2},ToDo));
		       -- Continue with the next variable and add i to L#0
		   if J != ideal(1_R) then ToDo = prepend({L#0|{R_i}, newL1, J},ToDo);
		   );
	      true));
     while next() do ();
     Answer	      
     )

-- This function saturates an integer lattice. It expects 
-- the matrix A, whose image is the lattice. 
Lsat = A -> LLL syz transpose LLL syz transpose A;

isCellular = method (Options => {ReturnCellVars => false})
isCellular Ideal := Ideal => o -> I -> (
     -- This function checks if a binomial ideal is cellular
     -- In the affirmative case it can return the cellular (regular) variables.
     R := ring I;
     cv := cellVars I;
     if cv == {} then prod := 1_R else prod = product cv;
     if I == saturate (I, prod) then (
	  -- I is cellular 
	  if o#ReturnCellVars then return cv
	  else return true;
	  )
     else false)

cellVars = method (Options => {CellVariables => null})
cellVars Ideal := Ideal => o -> I -> (
     -- This function computes the cell variables for a cellular ideal if necessary.
     if o#CellVariables === null then (
	  cv := {};
	  for i in gens ring I do if saturate (I,i) != substitute(ideal(1), ring I) then cv=cv|{i};
	  return cv;
	  )
     else o#CellVariables)

--  Setting up the PartialCharacter Type
PartialCharacter = new Type of HashTable;

partialCharacter = method (Options => {CellVariables => null})
partialCharacter Ideal := Ideal => o -> I -> (
     -- Will compute the partial character associated to a cellular binomial ideal.
     -- If the cell variables are known they can be given as an optional argument.
     
     vs := {}; -- This will hold the lattice generators
     vsmat := matrix "0"; -- Holds the matrix whose image is L 
     cl := {}; -- This will hold the coefficients
     R := ring I;
     CoeffR := coefficientRing R; -- needed to form terms below
     II := ideal;
     
     -- The input should be a cellular ideal 
     cv := cellVars(I, CellVariables=>o#CellVariables);
     ncv := toList (set gens R - cv);
     
     -- If there are no cellular variables, 
     -- the ideal is monomial and the partial character is zero:
     if cv == {} then (
	  return new PartialCharacter from {"J"=>{}, "L"=>matrix "0", "c"=>{1}};
	  );
     
     -- We need to construct this ring to properly extract coefficients below
     S := CoeffR(monoid [cv]);
     
     -- intersect I with the ring k[cv] and map to S
     if #ncv != 0 then (
     	  II = sub(eliminate (ncv, I),S);
	  )
     else (
	  -- S = R, stick with original def!
	  II = I;
	  );

     -- The partial character of the zero ideal is on the zero lattice.
     if ( II == 0 ) then (
	  for i in cv do vs = vs | { 0_ZZ };
	  cl = {1_ZZ};
	  return new PartialCharacter from {"J"=>cv, "L"=>transpose matrix {vs}, "c"=>cl};
	  );
     
     -- So, II is not zero:
     -- Let ts be the list of minimal generators, this uses that II\subset S !
     ts := entries mingens II;
     -- for each term, find the exponent vector
     oldmat := matrix "0";
     oldvs := {};
     for t in ts#0 do (
	  -- Want to check if we already have this generator included
	  
	  -- Save the old values
	  oldmat = vsmat;
	  oldvs = vs;
	  	  
	  -- compute new ones
	  vs = vs | {((exponents t)#0 - (exponents t)#1)};
	  vsmat = transpose matrix vs;
	  
	  -- Do we need the new generator ?
	  if image oldmat == image vsmat then (
	       -- Undo changes:
	       vsmat = oldmat;
	       vs = oldvs;
	       )
	  else (
	       -- So we have a new generator : update coefficient list
	       coeffs := entries ((coefficients(t))#1);
	       F := coefficientRing ring coeffs#1#0;
	       coe := for c in coeffs list lift(c#0,F);
               cl = cl | { sub ( -coe#1 / coe#0, CoeffR) };
	       );
	  );
     
     return (new PartialCharacter from {"J"=>cv, "L"=> transpose matrix vs , "c"=>cl});
     )

randomBinomialIdeal = (R,numge,maxdeg, maxwidth, homog) -> (	 
     -- Generate 'random' ideals for testing purposes. The distribution is completely heuristic and designed to serve
     -- internal purposes 
     -- Inputs: a ring R, the number of generators numgen, the maximal degree of each variable maxdeg,
     -- the maximal number of variables appearing in binomial, whether the output should be homogeneous
     
     -- Caveat: The result might simply be not homogeneous or of the given degree 
     -- due to deps between the random generators     
     
     -- Output: a 'random' binomial ideal.
     
     Rge := gens R;
     ng := #Rge;
     ge := {};
     ra := 0; split := 0;
     va := {}; m := {};
     z := for i in 0..ng-maxwidth-1 list 0;
     if homog then (
	  if odd maxwidth then maxwidth = maxwidth + 1;
	  for i in 0..numge do (
	       -- m will be a list of nonzero random exponents
     	       m = for j in 0..(maxwidth//2)-1 list (
	       	    ra = (random (2*maxdeg)) +1 ;
	       	    if ra > maxdeg then ra = -ra // 2;
	       	    ra
	       	    );
	       m = m | for j in 0..(maxwidth//2)-1 list (
		    ra = (random (2*maxdeg)) +1 ;
	       	    if ra > maxdeg then ra = -ra // 2;
	       	    -ra
		    );
     	       -- filling with zeros
	       m = random (m |z);
     	       ge = ge | {makeBinomial (R,m,1)};
  	       );  
	  )
     else (
     	  for i in 0..numge do (
	       -- m will be a list of nonzero random exponents
     	       m = for j in 0..maxwidth-1 list (
	       	    ra = (random (2*maxdeg)) +1 ;
	       	    if ra > maxdeg then ra = -ra // 2;
	       	    ra
	       	    );
     	       -- filling with zeros
	       m = random (m |z);
     	       ge = ge | {makeBinomial (R,m,1)};
  	       );
	  );
     ideal (mingens ideal(ge)))

isBinomial = I -> (
     -- Checking binomiality with a reduced gb.
     ge := flatten entries gens gb I;
     for g in ge do (
          if #(terms g) > 2 then return false;
	  );
     true)

isUnital = I -> (
     -- A unital ideal is generated by unital binomials and monomials.
     ge := flatten entries gens gb I;
     for g in ge do (
	  coeffs := sort flatten entries (coefficients g)#1;
	  if coeffs == {1} then continue;
	  if coeffs == { -1} then continue;
	  if coeffs == { -1 , 1} then continue;
	  return false;
	  );
     true)

     
nonCellstdm = {CellVariables=>null} >> o -> I -> (
     -- extracts the (finite) set of nilpotent monomials 
     -- modulo a cellular binomial ideal.
     R := ring I;

     cv := set cellVars(I, CellVariables=>o#CellVariables);
     -- Extracting  the monomials in the non-Cell variables.
     -- Problem: They may not live in R because R was extended on the way.
     -- This use of baseName is intended to fix a problem where the variables in cv 
     -- are actual variables of a ring over a field extension.
     ncv := value \ toList (set (baseName \ (gens R)) - baseName \ cv);
     
     -- We map I to the subring: kk[ncv]
     CoeffR := coefficientRing R;
     S := CoeffR(monoid [ncv]);
     J := kernel map (R/I,S); 
     basis (S/J))

maxNonCellstdm = {CellVariables=>null} >> o -> I -> (
     -- Computes the maximal monomials in the nilpotent variables

     cv := cellVars(I, CellVariables=>o#CellVariables);
     nm := flatten entries nonCellstdm (I,CellVariables=>cv);
     -- The following code extracts the maximal elements in a list of monomials 
     result := {};
     maxel := 0;
     while nm != {} do (
     	  maxel = max nm;
          -- Add maxel to the result
      	  result = result | {maxel};
          -- Delete everyone who is dividing maxel     
     	  nm = for m in nm list (if maxel // m != 0 then continue; m);
     );
     result)

makeBinomial = (R,m,c) -> (
     -- constructs the binomial associated to 
     -- exponent vector m and coefficient c in R
     var := gens R;
     posmon :=1_R;
     negmon :=1_R;
     for i in 0..#m-1 do (
     	  if m#i > 0 then (
		    posmon = posmon * var#i^(m#i)
		    )
	       else (
		    negmon = negmon * var#i^(-m#i)
		    );
	       );
     posmon - c*negmon)

idealFromCharacter = method();
idealFromCharacter (Ring, PartialCharacter) := Ideal => (R, pc) -> (
     -- Constructs the lattice Ideal I_+(c) in R
     -- R is a ring in which the ideal is returned
     -- The columns of A should contain exponent vectors of generators
     -- The vector c contains the corresponding coefficients which must lie
     -- in the coefficient ring of R.
     
     var := gens R;
     if pc#"L" == 0 then return ideal 0_R;
     cols := null;
     binomials := null;
     c := null;
     k := ring pc#"c"#0;
     
     idmat := matrix mutableIdentity(ZZ,#var);
     if pc#"L" == idmat then (
	  -- If A is the unit matrix we are lucky,
	  -- no saturation is needed.

	  -- We coerce the coefficients to R:
	  c = apply (pc#"c", a -> (sub (a,R)));
     	  cols = entries transpose pc#"L";
     	  binomials = for i in 0..numcols(pc#"L")-1 list makeBinomial (R,cols#i, c#i);	  
	  return ideal binomials
	  )
     else if set pc#"c" === set {1_k} then (
	  -- all coefficients are one, we can use 4ti2.
	  return toricMarkov (transpose pc#"L", R, InputType => "lattice");
	  )
     else (
     	  -- The general case, fall back to saturation in M2:
	  c = apply (pc#"c", a -> (sub (a,R)));
     	  cols = entries transpose pc#"L";    
     	  binomials = for i in 0..numcols(pc#"L")-1 list makeBinomial (R,cols#i, c#i);
     	  return saturate (ideal binomials, product var);
	  );
     )

latticeBasisIdeal = (R,L) -> (
     -- Constructs the lattice basis ideal (whose saturation is the lattice ideal)
     -- Convention is that L's columns generate the lattice.
     var := gens R;
     if L == 0 then return ideal 0_R;
     cols := null;
     binomials :=null;
     cols = entries transpose L;
     binomials = for i in 0..numcols L-1 list makeBinomial (R,cols#i, 1);
     ideal binomials)

saturatePChar = (pc) -> (
     -- This function saturates a partial character and returns the result
     -- as a list, even if the input was saturated.
          
     -- If the lattice is saturated, the character is saturated
     -- Note that this shortcircuits all problems with c being non-constant.
     if image Lsat pc#"L" == image pc#"L" then (
	  return {pc};
	  );
     
     -- The saturated lattice
     S := Lsat(pc#"L");
     -- The coefficient matrix :
     K := pc#"L" // S;
     
     -- print K;
     -- Now we find the (binomial) equations for the saturated character:
     numvars := numrows K;
     varlist := for i in 0..numvars-1 list value ("m"|i);
     Q := QQ(monoid [varlist]);
     eqs := idealFromCharacter (Q, (new PartialCharacter from {"J"=>gens Q, "L"=>K, "c"=>pc#"c"}));
     
     result := binomialSolve eqs;
     r := #result;
     i := 0;
     
     return(for i from 0 to r-1 list(
	  new PartialCharacter from {"J" => pc#"J", "L" => S, "c" => result#i}));
     )

satIdeals = (pc) -> (
     -- Computes all the ideals belonging to saturations of  
     -- a given partial character.
     satpc := saturatePChar(pc);
     -- The following is the smallest ring containing all new
     -- coefficients but not smaller than QQ
     F := ring satpc#0#"c"#0;
     if F === ZZ then F = QQ;
     Q := F(monoid [satpc#0#"J"]);
     for s in satpc list idealFromCharacter (Q, s))

binomialRadical = I -> (
     cv := isCellular (I, ReturnCellVars=>true);
     if not cv === false then (
	  return cellularBinomialRadical (I,CellVariables=>cv)
	  );
     -- In the general case
     print "Input not cellular, computing minimal primes ...";
     mp := binomialMinimalPrimes I;
     ideal mingens intersect mp)

cellularBinomialRadical = method (Options => {CellVariables => null}) 
cellularBinomialRadical Ideal := Ideal => o -> I -> (
     -- Computes the radical of a cellular binomial ideal
     R := ring I;
     cv := cellVars(I, CellVariables=>o#CellVariables);
     -- Get the non-cellular variables
     noncellvars := toList(set (gens R) - cv);
     M := sub (ideal (noncellvars),R);
     I + M)

binomialIsPrimary = I -> (
     -- Check if an arbitrary binomial ideal is primary
     -- first check for cellularity, then run the specialized check if the ideal is cellular.
     cv := isCellular (I, ReturnCellVars=>true);
     -- Can't check with logical comparison because the return value could be a list
     if cv === false then return false
     else cellularBinomialIsPrimary (I, CellVariables=>cv))

cellularBinomialIsPrimary = method (Options => {ReturnPrimes => false , ReturnPChars => false, CellVariables=> null})
cellularBinomialIsPrimary Ideal := Ideal => o -> I -> (
     -- Implements Alg. 9.4 in [ES96]
     -- I must be a cellular ideal, CellVariables can be given for speedup
     -- Returns the radical of I and whether I is primary
     -- if the option ReturnPrimes is true, then it will return 
     -- the radical in the affirmative case and two distinct associated primes
     -- otherwise
     -- if the option ReturnPChars is true then it will return partial Characters 
     -- of the primes instead. 
     -- If both are true then it will return characters.
     
     R := ring I;
     -- Only proper ideals are considered primary
     if I == ideal(1_R) then return false;      
     
     -- Handling of cell variables
     cv := cellVars(I, CellVariables=>o#CellVariables);

     -- Get the partial character of I
     pc := partialCharacter(I, CellVariables=>cv);
     noncellvars := toList(set gens R - cv);
     
     M := sub (ideal (noncellvars),R);
     -- the radical:
     rad := I + M;
     
     -- If the partial character is not saturated, the radical is not prime
     if image Lsat pc#"L" != image pc#"L" then (
	  print "The radical is not prime, as the character is not saturated";
	  satpc := saturatePChar pc;
	  if o#ReturnPChars then (
	       -- This one is the fastest, so check it first
	       return {{satpc#0#"J",satpc#0#"L",satpc#0#"c"}, {satpc#0#"J",satpc#0#"L",satpc#1#"c"}}
	       );
	  if o#ReturnPrimes then (
     	       F := ring satpc#0#"c"#0;
     	       S := F(monoid [satpc#0#"J"]);
	       M = sub(M,S);
	       ap1 := idealFromCharacter (S,satpc#0) + M;
	       ap2 := idealFromCharacter (S,satpc#1) + M;
	       -- Return two distinct associated primes:
	       return {ap1,ap2};
     	       )	   	       
	  else return false;
	  );
     
     -- If the radical is prime, then there still might be embedded
     -- primes that properly contain the radical. The remaining part
     -- finds such primes by examining quotients w.r.t (maximal)
     -- standard monomials. 
     
     -- The list of maximally standard monomials:
     maxlist := maxNonCellstdm (I,CellVariables=>cv);
     -- need to map to R to do colons with I
     f := map (R, ring maxlist#0);
     maxstdmon := maxlist / f;
     
     for m in maxstdmon do (
	  q := I:m;
	  -- Mapping down to k[E]:
--	  q2 := eliminate (noncellvars,q);
     	  q2 := q + M;
     	  -- I_+(sigma) was called prerad above:
	  if not isSubset(q2, rad) then (
	       -- creating some local names:
	       satqchar := saturatePChar partialCharacter (q,CellVariables=>cv);
	       if o#ReturnPChars then(
		    return {pc, {satqchar#0#"J",satqchar#0#"L",satqchar#0#"c"}}
		    );
	       if o#ReturnPrimes then (
		    F := ring satqchar#0#"c"#0;
     	       	    S := F(monoid [satqchar#0#"J"]);
	       	    M = sub(M,S);
		    ap2 := idealFromCharacter (S, satqchar);
		    return {rad, ap2 + M};
     	       	    )
	       else return false;
	       );
	  );
     if o#ReturnPChars then return {pc};
     if o#ReturnPrimes then return {rad};
     true)

binomialIsPrime = method (Options => {CellVariables=>null})
binomialIsPrime Ideal := Ideal => o -> I -> ( 
     -- A binomial ideal is prime if it is cellular and all its
     -- monomial generators have power one and the associated partial
     -- character is saturated.  (Corollary 2.6 in ES96 )

     -- Input: A Binomial Ideal and the cell variables if the ideal is cellular.
     -- Output: true if the ideal is a prime ideal, false otherwise
     
     -- test for cellularity:
     -- if cellular variables are given then we believe that I is cellular
     cv := null;
     if o#CellVariables === null then (
	  cv = isCellular (I, ReturnCellVars=>true);
     	  if cv === false  then return false)
     else cv = o#CellVariables;
     
     -- Check if non-cellular variables are all contained:
     R := ring I;
     ncv := toList(set (gens R) - cv); -- nilpotent variables x \notin E
     if not isSubset(promote(ideal ncv, R), I) then return false;

     -- Test if the partial character saturated:
     pc := partialCharacter (I, CellVariables=>cv);
     if image Lsat pc#"L" != image pc#"L" then return false;
     true)

binomialMinimalPrimes = method (Options => {Verbose=>false})
binomialMinimalPrimes Ideal := Ideal => o -> I -> (
     -- Algorithm from "Decompositions of Binomial Ideals" (AISM), 
     -- based on computing a cellular decomposition of the radical of I.
     if not isBinomial I then error "Input was not binomial";
     R := ring I;
     if I == ideal (1_R) then return {};
     ge := gens R;
     n := numgens R;
     Answer := {};
     L := null;
     IntersectAnswer := ideal(1_R);
     ToDo := {{{1_R},toList(0..n-1),I}};
     compo := 0;
     next := () -> (
	 if #ToDo === 0 then false
	 else (
	      L = ToDo#0;
	      ToDo = drop(ToDo,1);
	      if gens IntersectAnswer % L#2 == 0 then (
		   if o#Verbose then (
			<< "redundant component" << endl;
			);
		   )
	      else if #(L#1) === 0 then ( -- #(L#1) counts 'remaining variables to check'
                   compo = compo + 1; 		
		   newone := trim L#2;
		   if o#Verbose then (
			<< "components found so far: " << compo << endl;);
		   Answer = append(Answer,{newone, delete(1_R,L#0)});
		   IntersectAnswer = intersect(IntersectAnswer,newone);
		   if IntersectAnswer == I then ToDo = {})
	      else ( -- So, there are remaining variables #(L#1) is not zero
	           i := L#1#0; -- i is a variable under consideration
		   newL1 := drop(L#1,1); -- gets removed from the list
	           result := axisSaturate(L#2, i); -- compute saturation wrt i
		   J := result#1; -- Ideal
		   k := result#0; -- Saturation Exponent
		   if k > 0 then ( -- If a division was needed:
			J2 := L#2 + ideal(R_i); 
			J2 = saturate(J2, product L#0);
			if J2 != ideal(1_R) then
			    ToDo = prepend({L#0, newL1, J2},ToDo));
		   if J != ideal(1_R) then (
			ToDo = prepend({L#0|{R_i}, newL1, J},ToDo);
			);
		   );
	      true));
     while next() do ();
     -- print Answer;
     
     if o#Verbose then print "Decomposition done.";
          
     ncv := {};
     i := 0;
     j := #Answer;
     ME :=ideal; -* pc = {}; *- si := ideal; mp := {}; F := null; S:= null;
     for a in Answer do (
	  i = i+1;
	  if o#Verbose  then (
	       print ("Finding minimal primes of cellular component: " | toString i | " of " | toString j));
	  ME := ideal(toList(set (gens R) - a#1));
	  pc := partialCharacter (a#0, CellVariables=>a#1);
	  -- Check whether we have a radical ideal already:
	  if image Lsat pc#"L" == image pc#"L" then (
	       si = {a#0};
	       )
	  else (
	       si = satIdeals pc
	       );
	  F = coefficientRing ring si#0;
	  if F === QQ then S = R else S = F(monoid [ge]);
	  ME = sub (ME, S);
	  si = for i in si list sub(i,S);
	  si = si / (i -> trim (i + ME)); -- Adding monomials;
	  mp = mp | si;
	  );

     extractInclusionMinimalIdeals (joinCyclotomic mp, Verbose=>o#Verbose))

isBetween = (a,b,c) -> (
     -- Checks if a lies between b and c in divisibility order.
     -- b and c need not be comparable, or sorted.
     if (b%c == 0) then (
	  -- c divides b
	  if ( (a%c==0) and (b%a==0)) then return true;
	  )
     else if (c%b == 0) then (
	  if ( (a%b==0) and (c%a==0)) then return true;
	  );
     -- b and c are not comparable
     false)

cellularBinomialAssociatedPrimes = method (Options => {CellVariables => null, Verbose=>false}) 
cellularBinomialAssociatedPrimes Ideal := Ideal => o -> I -> ( 
     -- Computes the associated primes of cellular binomial ideal
     -- It returns them in a polynomial ring with the same variables as ring I,
     -- but potentially extended coefficient ring.

     R := ring I;
     
     cv := cellVars(I, CellVariables=>o#CellVariables);
          
     primes := {}; -- This will hold the list of primes
     ncv := toList(set (gens R) - cv); -- nilpotent variables x \notin E
     stdm := nonCellstdm(I,CellVariables=>cv); -- List of std monomials in ncv
     -- mapping to R:
     f := map (R, ring stdm);
     ml := flatten entries f stdm;
     
     if o#Verbose then(
	  if #ml == 1 then << "1 monomial to consider for this cellular component " << endl
     	  else <<  #ml << " monomials to consider for this cellular component" << endl;
	  );
     
     -- For a given partialCharacter, this hash table saves a witness monomial,
     -- and the corresponding lattice ideal.  The ideal is saved to potentially
     -- skip the ideal saturation further down.
     seenpc := new MutableHashTable;

     -- A dummy ideal and partial Characters:
     Im := ideal;
     pC := {}; sat := {};
     -- save 1 as the bottom witness
     seenpc#(partialCharacter (I, CellVariables=>cv))=({1_R}, I);
     todolist := delete(1_R, ml);
     -- While we have monomials to check
     while #todolist > 0 do (
--	  print ("On todolist: " | toString (#todolist));
	  -- sample a random monomial:
	  i := random(0, #todolist-1);
	  m := todolist#i;
	  Im = I:m;
	  pC = partialCharacter(Im, CellVariables=>cv);
	  if seenpc#?pC then (
	       -- We have seen this lattice: Time to prune the todolist
--	       print ("Todolist items before: " | toString (#todolist));
	       for n in seenpc#pC#0 do (
		    todolist = select (todolist , (mm -> not isBetween (mm, n, m))
		    ));
--	       print ("Todolist items after: " | toString (#todolist));
	       -- add m to the pruning list
	       todolist = delete(m, todolist);
	       addmon := true;
	       for mmm in seenpc#pC#0 do if m%mmm==0 then (addmon = false; break);
	       if addmon then seenpc#pC = (seenpc#pC#0 | {m}, seenpc#pC#1);
--	       print (#(seenpc#pC));
	       )   
	  else (
	       -- a new associated lattice
	       seenpc#pC = ({m} , Im);
	       todolist = delete(m, todolist);
	       )
	  );
--     print ("Todolist items: " | toString (#todolist));
     for pc in keys seenpc do (
	  -- If the lattice of pc is saturated, then we can skip the saturation (which would compute
	  -- a Markov basis (slow))
	  if image pc#"L" == image Lsat pc#"L" then (
	       primes = primes | {cellularBinomialRadical (seenpc#pc#1, CellVariables=>pc#"J")}
	       )
	  else (
	       -- need to actually saturate and potentially extend coefficients
	       sat = satIdeals pc;
	       -- If the coefficientRing is QQ, we map back to R
	       F := coefficientRing ring sat#0;
	       if F === QQ then (
	       	    f = map (R, ring sat#0);
	       	    sat = sat / f ;
	       	    )
	       else (
	       	    -- otherwise to the extended ring
	       	    -- this is necessary since satIdeals does not know about the nilpotent variables
	       	    S := F monoid R;
	       	    f = map (S, ring sat#0);
	       	    sat = sat / f;
	       	    );
	       primes = primes | sat;
	       )
	  );
     -- We need to remove duplicate elements and join all associated primes in an appropriate new ring that contains all
     -- their coefficients.
     primes = joinCyclotomic primes;
     M := sub (ideal ncv, ring primes#0);
     primes = primes / (I -> I + M);

     -- Computation of mingens is necessary as unique or toList + set combi won't do without
     unique (ideal \ mingens \ primes))

binomialAssociatedPrimes = I -> (
     if not isBinomial I then error "Input not binomial";
     cv := isCellular (I,ReturnCellVars=>true);
     if cv === false then (
	  print "Not yet implemented";
	  print "I will compute a primary decomposition and take radicals!";
	  bpd := BPD I;
	  print "Primary Decomposition found, taking radicals now:";
	  return binomialRadical \ bpd;
	  )
     else cellularBinomialAssociatedPrimes (I, CellVariables=>cv))

cellularAssociatedLattices = method (Options => {CellVariables => null})
cellularAssociatedLattices Ideal := Ideal => o -> I -> (
     -- Computes the associated lattices of a cellular binomial ideal
     -- WARNING: The definition might differ from the final definition in [KM11]
     
     R := ring I;
     cv := cellVars(I, CellVariables=>o#CellVariables);
     lats := {}; -- This will hold the list of lattices
     coeffs := {}; -- This will hold the values of the characters
     ncv := toList(set (gens R) - cv); -- nilpotent variables x \notin E
     -- print "Noncellvars"; print ncv;
     ml := flatten entries nonCellstdm(I,CellVariables=>cv); -- List of std monomials in ncv
     -- Coercing to R:
     f := map (R, ring ml#0);
     ml = ml/f;
     -- A dummy ideal and partial Characters:
     Im := ideal;
     pc := {};
     redundant := true;
     -- For each monomial, check if I:m shows an unseen lattice.
     for m in ml do (
	  -- print m;
	  Im = I:m;
	  -- We already know the cell variables in the following computation
	  pc = partialCharacter(Im, CellVariables=>cv);
	  if #lats == 0 then (
	       lats = {pc#"L"};
	       coeffs = {pc#"c"};
	       continue;
	       )
	  else (
	       redundant = false;
	       scan (lats, (l -> (if image l == image pc#"L" then redundant = true)))
     	       );
	  if redundant then continue
	  else (
	       lats = lats | {pc#"L"};
	       coeffs = coeffs | {pc#"c"};
	       );
      	  ); -- for m in ml	    
     {cv, lats, coeffs}) -- CellularAssociatedLattices

cellularEmbeddedLatticeWitnesses = method (Options => {CellVariables => null})
cellularEmbeddedLatticeWitnesses Ideal := Ideal => o -> I -> (
     -- Given a cellular binomial ideal whose radical is prime this
     -- function will produce witness monomials for embedded
     -- lattices.  Throw in these monomials to get rid of
     -- additional associated primes, i.e. compute Hull.

     R := ring I;
     cv := cellVars(I, CellVariables=>o#CellVariables);
     witnesses := {};
     lats := {}; -- This will hold the list of lattices
     ncv := toList(set (gens R) - cv); -- nilpotent variables x \notin E
     ml := flatten entries nonCellstdm(I,CellVariables=>cv); -- List of std monomials in ncv
     -- Coercing to R:
     f := map (R, ring ml#0);
     ml = ml / f;
     -- A dummy ideal and partial Characters:
     Im := ideal;
     pc := {};
     redundant := true;
     bottomlattice := partialCharacter (I, CellVariables=>cv);
     -- For each monomial, check if I:m has a different lattice:
     todolist := ml;
--     print ("Number of monomials to consider : " | toString (#todolist));
     while (#todolist > 0) do (
	  i := random(0, #todolist-1); -- a random monomial
	  m := todolist#i;
	  -- Now two possibilities:
	  -- if m witnesses an embedded lattice: Remove everything that is above m;
	  Im = I:m;
	  pc = partialCharacter(Im, CellVariables=>cv);
	  if (image pc#"L" == image bottomlattice#"L") then (
	       -- m is the same like 1. Remove everything between them
	       todolist = select (todolist, (mm) -> not isBetween(mm, 1,m))
	       )
	  else (
	       -- found a witness
	       witnesses = witnesses | {m};
	       todolist = for t in todolist list if t%m==0 then continue else t
	       );
--	  print ("Number of monomials to consider : " | toString (#todolist));
	  ); -- while
     witnesses) -- cellularEmbeddedLatticeWitnesses


minimalPrimaryComponent = method (Options => {CellVariables => null})
minimalPrimaryComponent Ideal := Ideal => o -> I -> (
     -- Input a cellular binomial ideal whose radical is prime.
     -- Output, generators for Hull(I)

     cv := cellVars(I, CellVariables=>o#CellVariables);
     if cv === false then error "Input to minimalPrimaryComponent was not cellular!";

     I + ideal (cellularEmbeddedLatticeWitnesses (I, CellVariables=>cv)))


binomialFrobeniusPower = (b,e) -> (
     -- returns the e-th Frobenius power of the binomial b
     -- i.e. (b_1)^e - (b_2)^e
     ((terms b)#0)^e - (- (terms b)#1)^e)

BCD = I -> binomialCellularDecomposition I 
BPD = I -> binomialPrimaryDecomposition I
BUD = I -> binomialUnmixedDecomposition I

binomialUnmixedDecomposition = method (Options => {Verbose=>false})
binomialUnmixedDecomposition Ideal := Ideal => o -> I -> (
     if not isBinomial I then error "Input was not binomial !";
     vbopt := o#Verbose;

     if vbopt then print "Running cellular decomposition:";
     cd := binomialCellularDecomposition (I, ReturnCellVars => true, Verbose=>vbopt);
     counter := 1;
     cdc := #cd;
     bud := {};
     if vbopt then print "Decomposing cellular components:";
     scan (cd , ( (i) -> (
		    if vbopt then (
	   	    	 print ("Decomposing cellular component: " | toString counter | " of " | toString cdc);
		    	 counter = counter +1;);
		    bud = bud | cellularBinomialUnmixedDecomposition (i#0, CellVariables => i#1,Verbose=>vbopt);
		    if vbopt then (
			 print "done";
			 );
		    ) -- right hand side of lambda term
	       ) -- lambda term
    	  ); -- scan
     if vbopt then print "Removing some redundant components...";
     -- In principle this does not make the intersection irredundant,
     -- but we don't want to run an exponential algorithm at this
     -- point.
     extractInclusionMinimalIdeals (bud, Verbose=>vbopt))

binomialPrimaryDecomposition = method (Options => {Verbose=>false})
binomialPrimaryDecomposition Ideal := Ideal => o -> I -> (
     -- The full binomial primary decomposition 
     -- starting from a not necessarily cellular binomial ideal
     
     if not isBinomial I then error "Input was not binomial !";
     if I == ideal (1_(ring I)) then return {};

     vbopt := o#Verbose;
     if vbopt then print "Running cellular decomposition:";
     cd := binomialCellularDecomposition (I, ReturnCellVars => true, Verbose=>vbopt);
     counter := 1;
     cdc := #cd;
     bpd := {};
     if vbopt then print "Decomposing cellular components:";
     scan (cd , ( (i) -> (
		    if vbopt then (
	   	    	 print ("Decomposing cellular component: " | toString counter | " of " | toString cdc);
		    	 counter = counter +1;);
		    bpd = bpd | cellularBinomialPrimaryDecomposition (i#0, CellVariables => i#1,Verbose=>vbopt);
		    if vbopt then (
			 print "done";
			 );
		    ) -- right hand side of lambda term
	       ) -- lambda term
    	  ); -- scan
      
     bpd = joinCyclotomic bpd;
     if vbopt then print "Removing some redundant components...";
     -- In principle this does not make the intersection irredundant,
     -- but we don't want to run an exponential algorithm at this
     -- point.
     extractInclusionMinimalIdeals (bpd, Verbose=>vbopt))

cellularBinomialUnmixedDecomposition = method (Options => {CellVariables => null, Verbose=>false}) 
cellularBinomialUnmixedDecomposition Ideal := Ideal => o -> I -> ( 
     -- computes the unmixed decomposition of a cellular ideal
     -- as defined in Ojeda/Sanchez
     vbopt := o#Verbose;
     cv := cellVars(I, CellVariables=>o#CellVariables);
     ncv := toList (set gens ring I - cv);
     
     -- Get the associated lattices (or better characters)
     aldata := cellularAssociatedLattices (I, CellVariables=>cv);

     -- We generate a list of pairs representing characters for the lattices:
     al := for i in 0..#(aldata#1)-1 list (aldata#1#i, aldata#2#i);
     
     -- if there is only one lattice, then I was unmixed
     if #al == 1 then return {I};

     R := ring I;
     CoeffR := coefficientRing R;
          
     -- Now find a chain among the associated lattices
     -- but finite index containment is not sufficient.
     -- We only need to check pairwise containments.
     pair := null;
     for l1 in al do (
	  -- break out if the inner loop assigned a pair:
	  if pair === null then break;
	  for l2 in delete(l1,al) do (
     	       if (isSubset (image l1#0, image l2#0)) and (rank image l1#0 < rank image l2#0) then (
		    -- found a comparable pair and thus embedded primes:
		    pair = (l1,l2);
		    -- break the inner loop.
		    break)));
     -- If no pair was found, then I is unmixed an we are done
     if pair === null then return {I};
     
     l1 := pair#0;
     l2 := pair#1;
     -- Identify a lattice vector in l2, but not l1
     L2cols := entries transpose l2#0;
     i := 0; -- Counter to identify a generator
     for col in L2cols do (
	  imc := image transpose matrix {col};
	  if rank intersect {imc, image l1#0} < 1 then (
	       -- found a vector
	       break;
	       );
	  -- Else keep going.
	  i = i+1;
	  );
     -- now i contains a suitable index
     b := sub(makeBinomial(CoeffR(monoid [cv]), L2cols#i, l2#1#i), R);
     
     -- We can't follow Section 4.1 of Ojeda/Sanchez because there is no 
     -- effective criterion to decide that mb^[e] will never lie in I, no
     -- matter how divisible e is.
    
     -- We take the approach of computing e_b by actually coloning.
     -- Stop condition: Find a binomial b^[e] such that I:b^[e] = I:b^[e]^\infty
     -- and this ideal is binomial.
     e :=1;
     Itest := I:b;
     while not ((isBinomial Itest) and ( Itest: binomialFrobeniusPower(b,e) == Itest)) do(
	  e = e + 1;
	  Itest = I:binomialFrobeniusPower (b,e);
	  );
     
     -- Now we have the right quotient and the right Frobenius power.
     -- So we start the recursion:
     flatten { 
	  cellularBinomialUnmixedDecomposition (Itest, CellVariables=>cv),
	  cellularBinomialUnmixedDecomposition (I + ideal binomialFrobeniusPower (b,e), CellVariables=>cv)
	  })

cellularBinomialPrimaryDecomposition = method (Options => {CellVariables => null, Verbose=>false}) 
cellularBinomialPrimaryDecomposition Ideal := Ideal => o -> I -> ( 
     -- computes the binomial primary decomposition of a cellular ideal
     -- I needs to be cellular. Cell variables can be given to speed up
     -- Implements algorithm 9.7 in ES96, respectively A5 in OS97
     vbopt := o#Verbose;
     cv := cellVars(I, CellVariables=>o#CellVariables);
     ncv := toList (set gens ring I - cv);
     ap := cellularBinomialAssociatedPrimes (I, CellVariables => cv,Verbose=>vbopt);
     -- If cv coincides with gens R, then the associated primes are their own minimal primary
     -- components (since in characteristic zero lattice ideals are radical):
     if #ncv == 0 then return ap
     else (
     	  -- Remove monomials from associated primes to get the lattice ideals
     	  f := map (ring ap#0, ring ncv#0);
     	  proj := (II) -> eliminate (f \ ncv,II);
     	  ap = ap / proj
	  );
     R := ring ap#0; -- All associated primes live in a common ring
     J := sub (I,R); -- get I over there to compute sums
     -- Here, contrary to what is stated in ES'96, we can not assume that J+ap#i is cellular.
     -- However, since Hull only wants the minimal primary component we can cellularize.

     -- Saturate product cv or saturate variable by variable?
     -- It seems to depend on the example which one is faster :(
--      cvsaturate := (p) -> (
-- 	  todo := cv;
-- 	  resu := p;
-- 	  while #todo > 0 do (
-- 	       resu = saturate (resu, sub(todo#0, R));
-- 	       todo = drop(todo,1)
-- 	       );
-- 	  resu);
     cvsaturate := (p) -> saturate (p, sub (product cv, R));
     ap / ( (P) -> minimalPrimaryComponent ( cvsaturate (P + J), CellVariables=>cv)))

extractInclusionMinimalIdeals = method (Options => {Verbose=>false})
extractInclusionMinimalIdeals List := List => o -> l -> (
    -- Computes the inclusion minimal elements in a list of ideals
    -- (like the minimal primes) Algorithm: For each ideal in the
    -- list, remove all ideals above it.  Note: This does not make an
    -- arbitrary intersection of ideals irredundant.  For example it
    -- would not reduce <x-y> \cap <x,y^2> \cap <x^2,y> where each of
    -- the last two components is redundant given the other two.

     if #l == 0 then return {};
     
     -- List to store the result, the flag marks elements that have been treated.
     result := for i in l list (i,false);

     -- While we have previously unconsidered elements:
     unconsidered := #l;
     while unconsidered > 0 do (
	 if o#Verbose then << unconsidered << " Ideals to check" << endl;
     	 p := (select(1, result, p -> p#1==false))#0 ; -- select returns list
	 result = for f in result list (
	     -- Check if p is contained in f which makes f redundant
	     if isSubset (p#0,f#0) then continue
	     else f);
         -- insert p again (flagged true) since it was removed before.
	 result = append (result,(p#0,true));
	 unconsidered = #(select (result, pp -> pp#1==false)));
     if o#Verbose then << #l-#result << " redundant ideals removed. Computing mingens of result.";
     for i in result list ideal mingens i#0)

-- The remaining code implements the solver for zero-dimensional unital
-- binomial ideals . We solve unital binomial equations using
-- modulo 1 arithmetic. The basic task is to solve a^n = 1^{k/m},
-- whose solutions are the equivalence classes of: k/nm, 1/n +
-- k/m, 2/n + k/nm,... , (n-1)/n + k/nm
          
-- The following function implements this:
Rooter = (n,q) -> (
     -- INPUT:
     -- n an integer
     -- q a rational number between zero and one representing k/m
     -- OUTPUT:
     -- The list of root-exponents:
     -- k/nm, 1/n + k/m, 2/n + k/nm,... , (n-1)/n + k/nm
     k := 0/1;
     m := 1;
     if q != 0 then (
	  m = denominator sub(q,QQ);
	  k = numerator sub(q,QQ);
	  );
     val := 0;
     roots := for i in 0..n-1 list (
	  val = i/n + k/(n*m);
	  if val > 1 then val = val - floor val;
	  val
	  );
     roots)

SolveMore = (binom,psol) -> (
     -- This function extends a partial solution further
     -- INPUT: A partial solution and a binomial which after plugging
     -- in the partial solutions is univariate
     -- OUTPUT: An extended partial solution

     -- Since Lex is a global order the true monomial comes first.
     mon := (terms binom)#0; -- The monomial in the new variable.
     
     -- we need the index of the variable that we will solve now
     -- <incomprehensable hack>
     ind := index (flatten entries gens radical monomialIdeal mon)#0;
     var := (flatten entries gens radical monomialIdeal mon)#0;
     -- </incomprehensable hack>
     
     rhs := (terms binom)#1; -- The right hand side which is a power
			     -- of a root of unity
			     
     erhs := flatten exponents rhs;
     
     newsols := {}; -- A list accumulating extended solutions
      
     -- If the binomial contains a common variable in both of its
     -- monomials then zero is a solution for this variable We are
     -- looking at erhs at position ind to determine this case
     
     roots := {};
     
     rhsvarpow := erhs#ind;
     
     if rhsvarpow > 0 then (
	  -- zero is a solution for variable ind
	  -- We fork of a new solution with entry "n" and divide by 
	  -- the offending variable
	  roots = {"n"};
     	  mon = lift(mon / var^rhsvarpow, ring mon);
	  rhs = lift(rhs / var^rhsvarpow, ring rhs);
	  erhs = flatten exponents rhs;
      	  );

     emon := flatten exponents mon;
     -- one element list containing the exponent
     n := (toList (set emon - set {0}))#0; 

      -- This needs to be done for each entry in psol:
      for onesol in psol do (
	   roots = {};
	   -- now determine the right hand side exponent from the
	   -- partial solutions.
	   zeroflag := false;    
       	   q := for v in 0..#erhs-1 list (
		-- First case: variable does not appear -> exponent 0
		if (erhs#v == 0) then 0
		else if onesol#v === "n" then (
		     -- if erhs > 0 and onesol has a "n", then the rhs is zero!
     	       	     zeroflag = true;
		     break 
		     )
		-- otherwise exponent times old exponent
		else erhs#v * onesol#v
		);
	   
	   if zeroflag and #roots == 0 then (
		roots = roots | {"n"};
		)
	   else (
		if not zeroflag then q = sum q;
		);

       	   -- now everything is set for the Rooter:
       	   roots = roots | Rooter (n,q);
       	   extensions := for r in roots list (
	    	for i in 0..#onesol-1 list if i==ind then r else onesol#i
	    	);
       	   newsols = newsols | extensions;
       	   );
      newsols)

binomialSolve = I -> (
     -- solver for zero-dim'l unital difference Binomial
     -- Ideals INPUT: I, the ideal    
     -- OUTPUT: The list of solutions in QQ(some root of unity)
     -- Note: Solutions will be returned with multiplicities.
     if not isUnital I then (
	  error "Sorry, only implemented for unital binomial ideals";
	  );
	  
     R := ring I;
     cd := binomialCellularDecomposition (I,ReturnCellVars=>true,Verbose=>false);
     exponentsols := flatten for c in cd list cellularBinomialExponentSolve (c#0,c#1);

     -- determine the least common denominator, ignoring nulls
     denoms := for i in flatten exponentsols list if i =!= null then denominator i else continue;
     -- If there are no denominators, the ideal was monomial
     -- and we return only (0,0,...,0) many times:
     if denoms === {} then (
	  zerosol:={for i in gens R list 0_R};
	  return for i in 1..#exponentsols list zerosol;
	  );
     lcd := lcm denoms;

     -- This is our standard. Coefficients are rational?
     C := QQ;     
     if lcd > 2 then (
	  -- print "Adjoining roots of unity is needed";
     	  C = cyclotomicField lcd;
	  );
     
     expo := q -> (
     -- This auxiliary function maps a quotient from QQ to its
     -- element in S
     if q === null then return 0_C;
     if q == 0 or q == 1 then return 1_C;
     if q == (1/2) then return -1_C;
     k := numerator sub(q,QQ);
     m := denominator sub(q,QQ);
     if m != lcd then k = k * sub(lcd / m,ZZ);
     return sub((C_0)^k,C);
     );
     
     sols := flatten exponentsols;
     sols = expo \ sols;
     pack (#(gens ring I),sols))

cellularBinomialExponentSolve = (I,cv) -> (
     -- Solves a zero dimensional cellular unital binomial ideal
     -- by constructing the appropriate cyclotomic field
     
     -- Input: a unital zero-dim'l binomial ideal and its list of
     -- cell variables
     
     -- Output: A list of solutions of the ideal 
     	  
     R := ring I;
     varlist := flatten entries vars R;
     RLex := newRing(R,MonomialOrder => Lex);
     if not dim I == 0 then error "Ideal to solve is not zero dimensional";
     
     -- First we need a Lex Groebner Basis of our ideal.     
     groeb := flatten entries gens gb sub(I,RLex);
     
     -- The data structure for a partial solution is as follows: It is
     -- a list of n-tuples where n is the number of variables. These
     -- tuples contain either rational numbers at already solved
     -- positions or the symbol '*' indicating that this position is
     -- unsolved and the special symbol null indicating that the
     -- solution(not exponent) is zero

     -- For each variable we check if it is a nilpotent variable, i.e.
     -- each solution of the ideal has coordinate zero there
     -- We also check how often we have to duplicate each solution in the
     -- end to account for monomials of higher order 
     dupnum := 1;     
     psols := {};
     for v in varlist do(
	  if isSubset (set {v},set cv) then(
	       -- Put side effects here:
	       -- Filling the list
	       psols = psols | {"*"};
	       )
	  else (
	       -- Put side effects here:
	       resu := axisSaturate(I, index v);
	       dupnum = dupnum * resu#0;
	       -- Filling the list
	       psols = psols | {null};
	       );
	  );
     
     -- If there are no cell variables: We are done
     if delete(null,psols) === {} then return for i in 0..(degree I)-1 list psols;
          
     -- The old solution for reference:
--     print "The following should coincide if no double sols";
--     print for v in varlist list if saturate(I,v) != I then null else "*"; 
--     print psols;
     
     -- make it a proper list of solutions
     psols = {psols};
     
     -- We solve on a log-scale for the exponents
     while #groeb > 0 do (
	  -- check if the current term is a binomial
	  if #(exponents groeb#0) > 1 then (
	       psols = SolveMore(groeb#0, psols);
	       );
     	  groeb = drop(groeb, 1);
	  );
     
     -- Now we duplicate:
     if dupnum > 1 then psols = for i in 1..dupnum list psols;
     flatten psols)

-- End of source code ---

beginDocumentation()

document {
        Key => Binomials,
        Headline => "a package for binomial ideals",

        EM "Binomials", " is a package for binomial ideals with a particular
        focus on intersection decompositions and associated primes.  For
        instance, if the input is a unital binomial ideal (that is generated
        by monomials and differences of monomials) then the function",
        TO binomialPrimaryDecomposition, "computes a primary decomposition into
        binomial ideals. To this end a cyclotomic field extension of the
        coefficient field may be necessary which is automatically constructed
        using the package ",TO Cyclotomic, ".", EM " Binomials", " also
        implements the data type ", TO partialCharacter, " (see [ES96]) and
        several convenience functions to transform binomials into exponent
        vectors and vice versa.  Those may be useful for manual inspection of
        binomial ideals.", "There is no special datatype for binomial ideals
        implemented, one just uses ", TO ideal, "s.",
	
	BR{},BR{},
	BOLD "Literature \n",
	UL {
	  LI {"[ES96] ", EM "Binomial ideals ", "(D. Eisenbud, B.Sturmfels, 1996).\n"},
	  LI {"[DMM10] ", EM "Combinatorics of binomial primary decomposition ", "(A. Dickenstein, L. Matusevich, E.Miller, 2010)\n"},
	  LI {"[OS00] ", EM "Cellular Binomial Ideals. Primary Decomposition of Binomial Ideals ", "(I. Ojeda, R. Piedra-Sanchez, 2000)\n"},
	  LI {"[Alt00] ", EM "The chain property for the associated primes of A-graded ideals ", "(K. Altmann, 2000)\n"},
	  LI {"[KM11] ", EM "Decompositions of commutative monoid congruences and binomial ideals ", "(T. Kahle, E. Miller, 2011)"}}}
   
document {
     Key => {binomialPrimaryDecomposition,
	  (binomialPrimaryDecomposition, Ideal)},
     Headline => "Binomial Primary Decomposition",
     Usage => "binomialPrimaryDecomposition I",
     Inputs => {
          "I" => { "a binomial ideal"} },
     Outputs => {
          {"a list of binomial primary components of I"} },
     "This routine returns a primary decomposition of I into binomial ideals.",
     EXAMPLE {
          "R = QQ[x,y,z]",
          "I = ideal (x*y-z, x*z-y^2)",
          "bpd = binomialPrimaryDecomposition I",
	  "intersect bpd == I"
          },
     "A synonym for this function is ", TO BPD, ".",
     Caveat => {"Currently it can not be guaranteed that the decomposition is irredundant, although serious attempts are made to reduce redundancy."},
     SeeAlso => BPD}

document {
     Key => {binomialUnmixedDecomposition,
	  (binomialUnmixedDecomposition, Ideal)},
     Headline => "Binomial Unmixed Decomposition",
     Usage => "binomialUnmixedDecomposition I",
     Inputs => {
          "I" => { "a binomial ideal"} },
     Outputs => {
          {"a list of unmixed components of I"} },
     "This routine returns an unmixed decomposition of a binomial ideal into binomial ideals. 
     The implemented algorithm is a variant of Algorithm 4 in [OS00].",
     EXAMPLE {
          "R = QQ[x,y,z]",
          "I = ideal (x^2, x*y, y^2, x*(z^3-1), y*(z^2-1))",
          "bud = binomialUnmixedDecomposition I",
	  "intersect bud == I"
          },
     "A synonym for this function is ", TO BUD, ".",
     Caveat=> "Apart from unmixedness, properties of the output decomposition are 
     defined only by the course of the algorithm, in particular it 
     is not mesoprimary decomposition of [KM11].",
     SeeAlso => BUD}

document {
     Key => BPD,
     Headline => "Binomial Primary Decomposition",
     "BPD is a synonym for ", TO binomialPrimaryDecomposition, "."}

document {
     Key => BUD,
     Headline => "Binomial Unmixed Decomposition",
     "BUD is a synonym for ", TO binomialUnmixedDecomposition, "."}

document {
     Key => {binomialCellularDecomposition,
          (binomialCellularDecomposition,Ideal),
	  [binomialCellularDecomposition,ReturnCellVars]},
     Headline => "Binomial Cellular Decomposition",
     Usage => "binomialCellularDecomposition I",
     Inputs => {
          "I" => { "a binomial ideal"} },
     Outputs => {
          {"a list of cellular ideals whose intersection is I or 
	    a list of pairs of these ideals and their cellular variables 
	    if the option ReturnCellVars => true is used"} },
     "A binomial ideal I is called cellular if modulo I every variable in 
     the polynomial ring is either a non-zerodivisor or nilpotent. 
     This routine returns a minimal cellular decomposition of a 
     binomial ideal.",
     EXAMPLE {
          "R = QQ[x,y,z]",
          "I = ideal (x*y-z, x*z-y^2)",
          "bcd = binomialCellularDecomposition I",
	  "intersect bcd == I",
     	  "binomialCellularDecomposition (I, ReturnCellVars=>true, Verbose=>false)"
          },
     "A synonym for this function is ", TO BCD, ".",
     "If the option ", TO Verbose, " is set (default), then output about the 
     number of components found so far will be generated.",
     SeeAlso => BCD}

document {
     Key => BCD,
     Headline => "Binomial Cellular Decomposition",
     "BCD is a synonym for ", TO binomialCellularDecomposition ,"."}

document {
     Key => {binomialRadical},
     Headline => "Radical of a binomial ideal",
     Usage => "binomialRadical I",
     Inputs => {
          "I" => { "a binomial ideal"} },
     Outputs => {
	  {"the radical of I"}},
     "If the input is a cellular binomial ideal then a very fast algorithm is used. 
     If one knows this and also the cellular variables then ", 
     TO cellularBinomialRadical, " should be used.",
     EXAMPLE {
          "R = QQ[x,y]",
	  "I = ideal (y^2, x*y-y, x^2-1)",
	  "binomialRadical I"
          },
     SeeAlso => cellularBinomialRadical}

document {
     Key => {cellularBinomialRadical,
	  (cellularBinomialRadical,Ideal)},
     Headline => "Radical of a cellular binomial ideal",
     Usage => "cellularBinomialRadical I",
     Inputs => {
          "I" => {"a cellular binomial ideal"} },
     Outputs => {
          {"the radical of I"} },
     "The radical of a cellular binomial ideal can be determined very quickly. If the 
     cellular variables are known they can be given as a list via the option ", TO CellVariables, ".",
     EXAMPLE {
	  "R = QQ[x,y,z]",
	  "I = ideal(y^3,y^2*z^2-x^3,x*y^2*z,x^3*z-x*y)",
	  "cv = isCellular (I,ReturnCellVars=>true)",
	  "cellularBinomialRadical (I,CellVariables=>cv)"
          },
     SeeAlso => binomialRadical}

document {
     Key => {binomialMinimalPrimes,
	  (binomialMinimalPrimes,Ideal)},
     Headline => "minimal primes of a binomial Ideal",
     Usage => "binomialMinimalPrimes I",
     Inputs => {
          "I" => {"a binomial ideal"}},
     Outputs => {
          {"the list of minimal primes of I"} },
     "The binomial minimal primes of a binomial ideal over QQ exist only in extension fields.",
     EXAMPLE {
	  "R = QQ[x,y,z]",
	  "I = ideal(y^3,y^2*z^2-x^3,x*y^2*z,x^3*z-x*y)",
	  "binomialMinimalPrimes I",
          },
     "If the option ", TO Verbose, " is set (default), then output about the 
     number of components found so far will be generated.",
     SeeAlso => binomialRadical}

document {
     Key => {binomialAssociatedPrimes},
     Headline => "Associated primes of a binomial ideal",
     Usage => "binomialAssociatedPrimes I",
     Inputs => {
          "I" => {"a binomial ideal"} },
     Outputs => {
          {"the list of associated primes of I"} },
     "First a cellular decomposition is run, then the associated primes of each cellular component are determined.",
     EXAMPLE {
	  "R = QQ[x,y]",
	  "I = ideal(x^2-y,y^2-x)",
	  "binomialAssociatedPrimes I",
          },
     SeeAlso => {binomialMinimalPrimes,cellularBinomialAssociatedPrimes}}

document {
     Key => {binomialIsPrime,
	  (binomialIsPrime,Ideal)},
     Headline => "test for primeness of a binomial ideal",
     Usage => "binomialIsPrime I",
     Inputs => {
          "I" => {"a binomial ideal"} },
     Outputs => {
          {"true or false, depending on whether I is a binomial prime ideal"} },
     "A binomial ideal is prime only if it is cellular. If the cellular variables ",
     "are known they can be given via the ", TO CellVariables, " option.",
     EXAMPLE {
	  "R = QQ[x,y]",
	  "I = ideal(x^2-y,y^2-x)",
	  "binomialIsPrime I",
          },
     SeeAlso => {cellularBinomialIsPrimary, CellVariables}}

document {
     Key => binomialIsPrimary,
     Headline => "test for primary binomial ideals",
     Usage => "binomialIsPrime I",
     Inputs => {
          "I" => {"a binomial ideal"}},
     Outputs => {
          {"true or false, depending on whether I is a primary binomial ideal"} },
     "A binomial ideal is prime only if it is cellular. If the cellular variables ",
     "are known, the function ", TO cellularBinomialIsPrimary, " should be used.",
     EXAMPLE {
	  "R = QQ[x,y,z]",
	  "I = ideal(x-y,z^3)",
	  "binomialIsPrimary I",
          },
     SeeAlso => {cellularBinomialIsPrimary, CellVariables}}

document {
     Key => {cellularBinomialIsPrimary,
	  (cellularBinomialIsPrimary,Ideal)},
     Headline => "test for primaryness of a binomial ideal",
     Usage => "cellularBinomialIsPrimary I",
     Inputs => {
          "I" => { "a binomial ideal"} },
     Outputs => {
          {"true or false, depending on whether I is a binomial primary ideal"} },
     "A binomial ideal is primary only if it is cellular. If the cellular variables ",
     "are known they can be given via the ", TO CellVariables, " option. ", "If the ideal is not primary, ",
     "either 'false' or two distinct associated primes can be returned. The behaviour can be changed using the options ",
     TO ReturnPrimes, " and ", TO ReturnPChars, ".",
     EXAMPLE {
	  "R = QQ[x,y]",
	  "I = ideal(x^2-1)",
	  "cellularBinomialIsPrimary (I,ReturnPrimes=>true)",
          },
     SeeAlso => {cellularBinomialIsPrimary, CellVariables, ReturnPrimes, ReturnPChars}}

document {
     Key => {binomialSolve},
     Headline => "solving zero-dimensional binomial Ideals",
     Usage => "binomialSolve I",
     Inputs => {
          "I" => {"a unital binomial ideal"}},
     Outputs => {
          {"the list of points in the zero locus of I in QQ[ww]"} },
     "The solutions of a set of unital binomial equations exist in a cyclotomic field. This function
     will compute the variety of a unital binomial ideal and construct an appropriate cyclotomic 
     field containing the entire variety (as a subset of the algebraic closure of QQ).",
     EXAMPLE {
	  "R = QQ[x,y,z,w]",
	  "I = ideal (x-y,y-z,z*w-1*w,w^2-x)",
	  "dim I",
	  "binomialSolve I",
	  "J = ideal (x^3-1,y-x,z-1,w-1)",
	  "binomialSolve J"
          },
     Caveat => {"The current implementation can only handle unital binomial ideals."},
     SeeAlso => Cyclotomic}

document {
     Key => {isCellular,
	  (isCellular,Ideal)},
     Headline => "testing for cellular binomial ideals",
     Usage => "isCellular I",
     Inputs => {
          "I" => {"a binomial ideal"}},
     Outputs => {
          {"true, or the list of cell variables if I is cellular, false otherwise."} },
     "This function is the standard way to compute the cellular variables.",
     EXAMPLE {
	  "R = QQ[x,y,z]",
	  "I = ideal (x-z^2,y^4)",
	  "isCellular I",
	  "isCellular (I, ReturnCellVars=>true)"
          },
     SeeAlso => {cellularBinomialAssociatedPrimes,binomialCellularDecomposition}}

document {
     Key => {isBinomial,
	     isUnital},
     Headline => "testing for unital binomial ideals",
     Usage => "isBinomial I; isUnital I",
     Inputs => {
          "I" => {"an ideal"}},
     Outputs => {
          {"true if I is binomial, or unital respectively."} },
     EXAMPLE {
	  "R = QQ[x,y,z]",
	  "isBinomial ideal(x^2)",
	  "isBinomial ideal(x-y+z,z)",
	  "isBinomial ideal(x^3-x)",
	  "isUnital ideal (x-z,z-y)",
	  "isUnital ideal (x+z)",
	  "isUnital ideal (x^2)"
          },
     SeeAlso => {isCellular}}

-- input related functions
document {
     Key => {makeBinomial},
     Headline => "make a binomial from an exponent vector and a coefficient",
     Usage => "makeBinomial (R,m,c)",
     Inputs => {
          "R" => {"a ring"},
	  "m" => {"a vector of exponents, one for each generator of R"},
	  "c" => {"an element of the coefficient ring of R"}},
     Outputs => {
          {"The binomial defined by the input data, as an element of R."} },
     EXAMPLE {
	  "R = QQ[x,y,z]",
	  "makeBinomial (R, [1,-1,-2], 10)"}}

document {
     Key => {latticeBasisIdeal},
     Headline => "construct the ideal whose generators correspond to generators of an integer lattice",
     Usage => "latticeBasisIdeal (R,L)",
     Inputs => {
          "R" => {"a ring"},
	  "L" => {"an integer matrix whose columns span the lattice."}},
     Outputs => {
          {"The unital lattice basis ideal in R, defined by L"} },
     "This function is only a very simple wrapper around ", TO makeBinomial,
     EXAMPLE {
	  "R = QQ[x,y,z]",
	  "L = matrix {{1,1},{-3,0},{0,1}}",
	  "latticeBasisIdeal (R, L)"}}

-- cellular stuff:
document {
     Key => {cellularBinomialAssociatedPrimes,
	  (cellularBinomialAssociatedPrimes,Ideal)},
     Headline => "Associated primes of a cellular binomial ideal",
     Usage => "cellularBinomialAssociatedPrimes I",
     Inputs => {
          "I" => {"a cellular binomial ideal"} },
     Outputs => {
          {"the list of associated primes of I"} },
     "If the cell variables are known, they can be given via the option ", 
     TO CellVariables, " otherwise they are computed.",
     EXAMPLE {
	  "R = QQ[x,y]",
	  "I = ideal(x^2-1,y-x)",
	  "cv = isCellular (I,ReturnCellVars=>true)",
	  "cellularBinomialAssociatedPrimes (I,CellVariables=>cv)"
          },
     SeeAlso => binomialAssociatedPrimes}    

document {
     Key => {cellularBinomialPrimaryDecomposition,
	  (cellularBinomialPrimaryDecomposition,Ideal)},
     Headline => "Primary decomposition of a cellular binomial ideal",
     Usage => "cellularBinomialPrimaryDecomposition I",
     Inputs => {
          "I" => {"a cellular binomial ideal"}},
     Outputs => {
          {"a binomial primary decomposition of I"}},
     "If the cell variables are known, they can be given via the option ", 
     TO CellVariables, " otherwise they are computed.",
     EXAMPLE {
	  "R = QQ[x,y]",
	  "I = ideal(x^3-1,y-x)",
	  "cv = isCellular (I,ReturnCellVars=>true)",
	  "pd = cellularBinomialPrimaryDecomposition (I,CellVariables=>cv)",
	  "mingens \\ pd"
          },
     Caveat => {"This function will not return minimal generators for performance reasons."},
     SeeAlso => binomialAssociatedPrimes}

document {
     Key => {cellularBinomialUnmixedDecomposition,
	  (cellularBinomialUnmixedDecomposition,Ideal)},
     Headline => "Unmixed decomposition of a cellular binomial ideal",
     Usage => "cellularBinomialUnmixedDecomposition I",
     Inputs => {
          "I" => {"a cellular binomial ideal"}},
     Outputs => {
          {"an unmixed decomposition of I"}},
     "If the cell variables are known, they can be given via the option ", 
     TO CellVariables, " otherwise they are computed.",
     EXAMPLE {
	  "R = QQ[x,y]",
	  "I = ideal(x*(y^3-1),x^2)",
	  "cv = isCellular (I,ReturnCellVars=>true)",
	  "ud = cellularBinomialUnmixedDecomposition (I,CellVariables=>cv)"
          },
     SeeAlso => binomialUnmixedDecomposition}

document {
     Key => {partialCharacter,
	  (partialCharacter,Ideal)},
     Headline => "Computing the partial character of a cellular binomial ideal",
     Usage => "partialCharacter I",
     Inputs => {
          "I" => {"a cellular binomial ideal"}},
     Outputs => {
          {"the ", TO PartialCharacter}},
     "If the cell variables are known, they can be given via the option ", 
     TO CellVariables, " otherwise they are computed.",
     EXAMPLE {
	  "R = QQ[x,y]",
	  "I = ideal(x^3-1,y-x)",
	  "cv = isCellular (I,ReturnCellVars=>true)",
	  "pc = partialCharacter (I,CellVariables=>cv)",
          },
     Caveat => {"If the input is not cellular the behaviour is undefined. Cellularity is not checked."}}

document {
     Key => {idealFromCharacter,
	   (idealFromCharacter,Ring,PartialCharacter)},
     Headline => "Generate a lattice ideal from a character.",
     Usage => "idealFromCharacter (R, rho)",
     Inputs => {
	  "R" => {"a ring to contain the output ideal"},
	  "rho" => {"a ", TO partialCharacter } },
     Outputs => {
	  {"the lattice ideal corresponding to rho"}
	  },
     Caveat => {"The variables occurring in rho#\"J\" must be variables of R."},
     EXAMPLE {
	  "R = QQ[x,y]",
	  "I = ideal(x^3-1,y-x)",
	  "cv = isCellular (I,ReturnCellVars=>true)",
	  "pc = partialCharacter (I,CellVariables=>cv)",
	  "idealFromCharacter (R,pc) == I"}}

document {
     Key => {randomBinomialIdeal},
     Headline => "Random Binomial Ideals",
     Usage => "randomBinomialIdeal (R,n,d,w,h)",
     Inputs => {
          "I" => {"a ring for the output"},
	  "n" => {"number of generators of the output "},
	  "d" => {"maximum degree of each variable" },
	  "w" => {"number of variables in each generator "},
	  "h" => {"should the generators be 'as homogeneous as possible'"} },
     Outputs => {
           {"a random ideal"} },
     "The exponents are drawn at random from {-d,...,d}. All coefficients are set to 1.",
     EXAMPLE {
	  "R = QQ[a..x]",
	  "randomBinomialIdeal (R,6,2,4,true)",
     	  "randomBinomialIdeal (R,3,4,10,false)"
          },
     "This function is mostly for internal testing purposes. Don't expect anything from it.",
     Caveat => "Minimal generators are produced. These can be less than n and of 
     higher degree. They also need not be homogeneous."}

document {
     Key => {extractInclusionMinimalIdeals,
	  (extractInclusionMinimalIdeals,List)},
     Headline => "Extract inclusion minimal ideals from a list of ideals",
     Usage => "extractInclusionMinimalIdeals L",
     Inputs => {
          "L" => {"a list of ideals"} },
     Outputs => {
          {"the list with some redundant ideals removed"}},
     EXAMPLE {
	  "R = QQ[a,b]",
	  "L = {ideal(a^4),ideal(a^3),ideal(a^5),ideal(b^2*a) }",
	  "extractInclusionMinimalIdeals L",
          },
     "This function is mostly for internal purposes.",
     Caveat => "The resulting list may be not irredundant, because I_1 
     \\subset I_2 \\cap I_3 is not checked."}

document { Key => {CellVariables, [partialCharacter,CellVariables],
     [cellularBinomialRadical,CellVariables], [binomialIsPrime,CellVariables],
     [cellularBinomialIsPrimary,CellVariables], [cellularBinomialAssociatedPrimes,CellVariables],
     [cellularBinomialPrimaryDecomposition,CellVariables],
     [cellularBinomialUnmixedDecomposition,CellVariables]},
     Headline => "cellular variables",
     "The cellular variables of a binomial ideal are the variables which are non-zerodivisors modulo
     that ideal. With this option these variables, if known in advance, can be handed over to
     specialized functions for cellular ideals. ",
     SeeAlso => {cellularBinomialPrimaryDecomposition,cellularBinomialAssociatedPrimes}}

document {
     Key => {ReturnCellVars,
	  [isCellular,ReturnCellVars]},
     Headline => "return the cellular variables",
     "The cellular variables of a binomial ideal are the variables which are non-zerodivisors 
     module that ideal. If this option is set to 'true' then binomialCellularDecomposition will
     return the set of variables for each of its outputs",
     EXAMPLE {
	  "R = QQ[x,y,z]",
          "I = ideal (x*y-z, x*z-y^2)",
          "bcd = binomialCellularDecomposition (I,ReturnCellVars=>true)"}}

document {
     Key => {ReturnPrimes,
     	  [cellularBinomialIsPrimary,ReturnPrimes]},
     Headline => "return two associated primes",
     "If cellularBinomialIsPrimary does not return true it can either return 'false' or two associated primes.
     If this option is set then two associated primes are returned. If ReturnPChars is set too, then partial
     characters will be returned.",
     EXAMPLE {
	  "R = QQ[x,y,z]",
          "I = ideal (x^2-1)",
          "cellularBinomialIsPrimary (I,ReturnPrimes=>true)",
          },
     SeeAlso => {ReturnPChars, cellularBinomialIsPrimary}}

document {
     Key => {ReturnPChars,
	  [cellularBinomialIsPrimary,ReturnPChars]},
     Headline => "return two partial characters",
     "If cellularBinomialIsPrimary does not return true it can either return 'false' or two associated primes.
     If this option is set then two partial characters of distinct associated primes are returned. 
     If ReturnPrimes is set too, then partial characters will be returned.",
     EXAMPLE {
	  "R = QQ[x]",
          "I = ideal (x^2-1)",
          "cellularBinomialIsPrimary (I,ReturnPChars=>true)",
          },
     SeeAlso => {ReturnPrimes, cellularBinomialIsPrimary}}

document {
     Key => {[binomialPrimaryDecomposition, Verbose],
	  [binomialUnmixedDecomposition, Verbose],
	  [binomialCellularDecomposition,Verbose],
	  [binomialMinimalPrimes,Verbose],
	  [cellularBinomialAssociatedPrimes,Verbose],
	  [cellularBinomialPrimaryDecomposition,Verbose],
	  [extractInclusionMinimalIdeals,Verbose],
	  [cellularBinomialUnmixedDecomposition,Verbose]},
     Headline => "generate informative output",
     "If this option is set, functions will generate additional output. Defaults to false"}

document {
     Key => PartialCharacter,
     Headline => "the class of all partial characters",
     "In ", TO Binomials , " the partial character of a cellular binomial ideal is represented 
     as an object of class ", TO PartialCharacter,".  It contains the following three data:",
     UL { {"J -- the cellular variables"},
	  {"L -- a matrix whose columns are generators for the lattice"},
	  {"c -- the list of values the character takes on the generators"}}}

----- TESTS -----
TEST ///
R = QQ[a..f]
I = ideal(b*c-d*e,b*e*f-a*c,a*d*f-d*e,a*b*f-c*d,d^2*e-e,a*d*e-d*e,a*c*e-d*f) 
bpd = BPD I;
assert (intersect bpd == sub(I,ring bpd#0))
///

TEST ///
R = QQ[c,d,x,y,z,w];
I = ideal(x^3*d^2*w-c*z^2,x^5*y^2-w^7,w^3-z^8,z^2-d*w*x^7)
time bpd = binomialPrimaryDecomposition (I,Verbose=>false);
assert (intersect bpd == I)
///

TEST ///
S = QQ[R00,U00,R01,D01,U01,R02,D02,L10,U10,L11,D11,U11,L12,D12];
I = ideal (U00*R01-R00*U10,R01*D11-D01*R00,D11*L10-L11*D01,
           L10*U00-U10*L11,U01*R02-R01*U11,R02*D12-D02*R01,
	   D12*L11-L12*D02,L11*U01-U11*L12);
bpd = BPD I;
assert (intersect bpd == I)
///

TEST ///
R = QQ[a..h]
I = ideal(d*g*h-e*g*h,a*b*g-c*f*h,a*b*c-e*g*h,c*f*h^2-d*f,e^2*g*h-d*h,b*d*f*h-c*g,a*d*f*g-c*e,b*c*e*g-a*f,a*b*e*f-c*d);
bpd = binomialPrimaryDecomposition (I,Verbose=>false);
assert (intersect bpd == I); 
///

TEST ///
-- Cyclotomic stuff
R = QQ[x,y,z]; I = ideal (x^2*y-z^2, x^2-z^3, y^4-1); 
bpd = BPD (I,Verbose=>false);
assert (intersect bpd == sub(I, ring bpd#0));
///

TEST ///
-- Unmixed Decomposition
R = QQ[x,y,z];
I = ideal (x^2, y^2, x*y, x*(z^3-1), y*(z^2-1))
bud = BUD (I, Verbose=>false);
assert(intersect bud == I);
///

TEST ///
-- minimal primes:
-- The 1.0 version of Binomials.m2 would return 6 minimal primes here
-- because redundancy was not taken care of properly
R = QQ[a,b,c,d,x]
I = ideal (a^2 - b^2, c^2 - d^2, x*(a*d-b*c), x*(a*c-b*d))
mp = binomialMinimalPrimes I
assert (intersect mp == I)
assert (#mp == 4)
///

TEST ///
-- remove redundant:
R = QQ[x]
I1 = ideal (x)
I2 = ideal (x^2)
I3 = ideal (x^3)
for L in permutations {I1,I2,I3} do (
    assert (#(extractInclusionMinimalIdeals L) == 1);
    )
///

TEST ///
R = QQ[x,y]
assert(binomialIsPrime ideal x^2 == false)
assert(binomialIsPrime ideal (x^2-y^2) == false)
assert(binomialIsPrime ideal (x-y) == true)
///

end
------------------------------------------------------------
restart
uninstallPackage "Binomials"
installPackage "Binomials"
check "Binomials"

restart
needsPackage "Binomials";
S = QQ[x,y];
b = makeBinomial (S, [2,-3], 5)
isBinomial ideal b
I = ideal(x^2-x*y, x*y-y^2);
isCellular I
binomialIsPrimary I
binomialRadical I
binomialPrimaryDecomposition I

L = binomialPrimaryDecomposition ideal(x^3-1)
L#0

P = binomialPrimaryDecomposition ideal (x^10000 * (y-1), x^10001)
radical P#0
P#1