CoCoALib Examples

ex-empty.C This is a template file for example programs. The program itself does nothing whatsoever.
Make a copy of this file (called "foo.C", say) and put your code 
inside the procedure "program".                                  
To compile your file in the examples directory just do this:       
  make foo                                                         


ex-c++.C This is an example showing some basic C++ you need to know to use CoCoALib
printing, vector, ... 


ex-AlexanderDual.C Program showing `AlexanderDual' and `PrimaryDecomposition' on monomial ideals. If Frobby is available, it is used too.
This example shows how to compute the `AlexanderDual' and the       
`PrimaryDecomposition' of monomial ideals.  These operations are    
offered by both CoCoALib and the external library Frobby.  This     
program shows how to check whether Frobby is available, and if so,  
how to call its functions with CoCoALib data.                       


ex-ApproxPts1.C A short example showing how to use the approximate point preprocessing algorithms. See the file ex-ApproxPt1.in for a sample input.
A short example which reads a set of approximate points (with common epsilon)
and then applies the various preprocessing algorithms to them.  It prints out
the resulting preprocessed set with the corresponding weights, and the time taken.

ex-BigInt1.C Program showing basic use of BigInt values: creation, printing, and some simple arithmetic.
This program illustrates basic operations on BigInt values, showing that   
they can be used much like normal C++ ints except that there is a almost   
no limit on the magnitude of the values.                                   
NB If you need extreme efficiency then use the GMP library directly.       
Contrast this example with ex-RingZZ1.                                     


ex-BigInt2.C Program to calculate the modular inverse of a number. You must give as input the modulus and the residue; the residue need not be reduced.
This program illustrates that BigInt values can be used much like normal C++ 
ints except that there is a almost no limit on the magnitude of the values.  
NB If you need extreme efficiency then use the GMP library directly.         
Contrast this example with ex-RingZZ1.                                       


ex-BigInt3.C Program to find a (probable) prime with a specified number of bits.
This program shows that BigInts can be used much like normal C++ ints
with the advantage that there is almost no limit on the magnitude of 
the values.  Here we generate random BigInts and test them for being 
probable primes -- stopping as soon as we find a likely prime.       
NB If you need extreme efficiency then use the GMP library directly. 


ex-BigRat1.C Program illustrating basic use of BigRat values (i.e. rational numbers) showing that they can be used with a natural syntax.
Program giving example of basic arithmetic with exact rational numbers 
represented as values of type BigRat.  The syntax recalls that used for    
the built-in C++ numerical types.  Emphasis is on convenience rather   
utmost execution speed.  To understand better the difference between   
a BigRat value and an element of the ring RingQ, contrast this example     
with ex-RingQ1.C.                                                      


ex-bool3.C This program shows a simple use of three-state booleans.
This program shows a simple use of three-state booleans.        
We define a quick primality test which is guaranteed to be fast 
but which sometimes has to return a verdict of "Don't know" so
it can keep its guarantee of speed.  We then see how often the  
quick test gives a definite answer, and how often it has to say 
"Don't know".                                                 


ex-BuildInfo.C This is a very short example showing what you can do with BuildInfo.
BuildInfo::PrintAll gives important information in the (enormously 
unlikely :-) event that you need to report a bug in CoCoALib. 


ex-decimal1.C This program makes simple use of the decimal conversion functions.
Example of use of MantissaAndExponent and MantExp structure.              
Also use of FloatStr to convert a integer/rational into a decimal string. 


ex-DivMask1.C This example program shows the use of DivMasks. See also the example program ex-PPWithMask1.C
We show how to use DivMasks directly -- it is a bit tedious!             
See also the example ex-PPWithMask1.C, which has a friendlier interface. 
We show how the various different DivMaskRules can be selected.          


ex-DivMask2.C This example program performs some divisibility tests on PPs using DivMasks; it measures the effectiveness of the various DivMaskRules. See ex-PPWithMask2 for some similar timing tests.
This example program illustrates the effectiveness of the various    
DivMaskRules when using DivMasks as a quick non-divisibility check.  
Using DivMasks to check divisibility we can obtain two answers:      
'Surely not' or 'Maybe'.  The intention here is to see how often     
'Maybe' really means 'Yes, divisible'.  We see that the effectiveness
depends also on the presence of unused indeterminate in the PPMonoid.


ex-DynamicBitset1.C This example program shows the use of DynamicBitsets.
We show how to convert to and from PPMonoidElem.             
We list the available operations which are a lot faster than 
the corresponding ones on PPMonoidElems.                     
By default DynamicBitsets are printed as STL bitsets, i.e.   
0th bit in the rightmost position.  We show other options.   

Note that the ordering is xel, i.e. like lex but starting    
the comparison from the position with highest index (as they 
are printed by default)

ex-factor1.C This example shows how to interpret the result of a factorization.
This example shows how to interpret the result of a factorization. 
It creates a ring element (belonging to a polynomial ring), and    
factorizes it.  The result is a "factorization object".  We show 
how to access the various parts of this object.                    


ex-frobby1.C This program shows what can be computed in CoCoALib using Frobby: a library for ...


ex-GMPAllocator1.C Program to find lengths of 3n+1 sequences -- using CoCoA::GMPAllocator
This example shows how to specify that a CoCoA::GMPAllocator be used for 
managing the memory for small GMP values.  If you do computations        
involving many small big-integers (up to about 40 decimal digits) then   
the custom allocator may give slightly better run-time performance (with 
debugging turned off!)  The argument to the constructor for GlobalManager
indicates that the CoCoA::GMPAllocator is to be used.                    


ex-GMPAllocator2.C Program comparing memory allocators for GMP values.
This example shows the various ways of specifying the memory manager to  
be used by the GMP library.  The choice of memory manager is indicated as
an argument to the GlobalManager constructor.  Here we illustrate four   
choices: the CoCoALib default, the system allocator, the specialized     
GMPAllocator (with and without explicit indication of the slice size).   
The program measures the speed of computation with these various choices.


ex-hilbert1.C This example is just for testing the Hilbert code. It might disappear as soon as HilbertSeries is included in CoCoALib.
This code also shows how to create the "chess examples".           


ex-io.C Program to demonstrate changing the global i/o channels.
This example shows how to change the global output channel GlobalOutput. 
The most important point is that the variable  out  is at top-level      
inside program().  If it were inside the then-block, the ofstream        
would be destroyed as soon as control leaves the then-block; and at      
that point the global output stream would contain a dangling reference.  


ex-matrix1.C Example program illustrating the creation of matrices, and some operations on them.
Example program illustrating the creation of matrices, and some 
basic operations on them. 


ex-matrix2.C Example program illustrating the creation of matrix views, and some effects of "aliasing". Examples of matrix views include transposes submatrices, block matrices, and concatenated matrices.
Example program illustrating the creation of matrix views, and some    
effects of "aliasing", i.e. where there is more than one way to refer
to a single entry of the matrix.  We gives examples of creating various
views: ZeroMat, IdentityMat, transpose, submat, BlockMat, ConcatHor and
ConcatVer.

ex-matrix3.C This program shows how to solve linear systems (matrix equations).
This program shows how to solve linear systems (matrix equations). 
At the moment linear system solving is only partially implemented. 
It will work if the matrix is over a field; otherwise it may fail. 


ex-module1.C Example program illustrating the creation of free modules, and some operations on them.
Please note that the module code is still rather young. 


ex-MVT.C Example of use of the Mayer-Vietoris trees.
Example of use of the Mayer-Vietoris trees.  


ex-NF.C Example program illustrating an implementation of Normal Remainder wrt a list of polynomials. If the list is a Groebner Basis, NR returns the Normal Form.
This is just an example!  If you want to compute Normal Forms 
you should use the library function "NF".                   


ex-Normaliz1.C This program shows what can be computed in CoCoALib using Normaliz: a library for computations in affine monoids, vector configurations, lattice polytopes, and rational cones.
NewConeLong   -- gives more speed  
NewConeBigInt -- gives reliability 


ex-Normaliz2.C This example reads a normaliz input file and computes the Hilbert basis. It also shows how to set some libnormaliz flags
the input file can be specified in the source code
                                                           


ex-NumTheory1.C This program illustrates the use of some basic number theoretic functions.
This programs show how to use some of the basic number theoretic functions.
Many of the examples use machine integers for convenience, but all the     
functions also work with BigInt values (except NextPrime and PrevPrime).   


ex-OrderingGrading1.C Predefined and user-defined orderings and gradings on PPMonoid and PolyRing.
Each ordering is degree-compatible with grading over Z^GradingDim 
i.e. the grading is given by the first GradingDim rows            
of the ordering matrix.                                           


ex-PolyInput1.C This program shows a way to read a polynomial from the input.
ex-PolyIterator1.C Program showing how to iterate through "sparse" polynomials.
ex-PolyIterator2.C Program showing how to homogenize a sparse polynomial using iterators.
This is just an example!  If you want to homogenize polynomials  
you should use the library function "homog".                   


ex-PolyRing1.C Example showing how to create some simple polynomial rings. It also shows some of the operations specific to elements of PolyRings. See also ex-ring2.C
This example program exhibits two things: various ways of creating 
polynomial rings, and several operations specific to elements of a 
polynomial ring.                                                   
In the procedure "program" there are examples of creating        
polynomial rings.                                                  
In the procedure "SomeComputations" there are brief examples of  
the operations specific to elements of PolyRings (e.g. deg).       
See also ex-ring2.C.                                               


ex-PolyRing2.C Example showing how to write polynomials using "monomial" See also ex-PolyRing1.C
Because of C priority on operator "^" we cannot overload it  
to define powers, as a consequence writing power-products can  
be quite tedious or difficult to read.                         
Here we show how to write a simple function to create exponent 
vectors to be passed to "monomial".                          
I wish there were a better way to initialise a C++ vector...   


ex-PPMonoidElem1.C Example of use of power products and PPMonoids. Program exhibiting most functions on power products.
ex-PPMonoidElem2.C Example of use of power products in different PPMonoids. Program exhibiting timings of the different implementations.
The implementations of PPMonoids are optimized for different uses:  
PPMonoidEv:   stores the Exponent vector                            
              good for accessing the exponents, slow for ordering   
PPMonoidOv:   stores the Order vector                               
              good for ordering, slow for accessing the exponents   
PPMonoidEvOv: stores the Exponent vector and the Order vector       
              good for accessing the exponents and for ordering     
              uses more memory and takes more time to assign        
PPMonoidBigEv: stores the Exponent vector as BigInt's               
              necessary if you use big exponents (>2^10)            
              obviously slow   


ex-PPMonoidHom1.C This is a template file for example programs. The program itself does nothing whatsoever.
Make a copy of this file (called "foo.C", say) and put your code 
inside the procedure "program".                                  
To compile your file in the examples directory just do this:       
  make foo                                                         


ex-PPWithMask1.C This example program shows the use of PPWithMasks for testing divisibility between PPs. Compare with ex-DivMask1.C.
We show how to use PPWithMasks for testing divisibility.      
This program is very similar to ex-DivMask1.C.  The main      
differences are that this program is shorter and clearer, and 
it does a proper job of testing divisibility (even when the   
 useless null rule is used).                                  


ex-PPWithMask2.C This example program performs some divisibility speed tests using PPWithMasks; it shows the difference in speed which can be achieved using various DivMaskRules.
This example program test the speed of the divisibility test  
on values of type PPwithMask.  The main aim is to show that   
different DivMaskRules can produces differing behaviour, and  
which rule is best depends on the problem (e.g. few indets    
and high degrees, or many indets and low degrees).  Here we   
see also that unused indets can affect the speed.             
In case you're interested, the program ex-DivMask2 measures   
the effectiveness of the various DivMaskRules.                


ex-QuotientBasis.C Program showing how to compute a quotient basis of a 0-dimensional ideal.
The function "QuotientBasis" is now included in CoCoALib,          
so this example is a lot shorter than it was before version 0.9943.  
It returns a vector of PPMonoidElem.


ex-RandomSource1.C This program shows the easiest way to produce random booleans, machine integers, and big integers.
This program uses GlobalRandomSource() to generate uniformly   
distributed random bits/booleans, machine integers in a given  
range, and big integers in a given range.  For the booleans and
machine integers it produces a histogram.                      
Use of globals could be dangerous in multi-threaded programs.  


ex-RandomSource2.C This program shows basic use of a RandomSource object to produce random booleans, machine integers, and big integers. Also shows how to seed and reseed a RandomSource. This program uses explicitely a RandomSource object to generate distributed random bits/booleans, machine integers in a given range, and big integers in a given range.
This program uses explicitely a RandomSource object to generate 
distributed random bits/booleans, machine integers in a given  
range, and big integers in a given range.                      


ex-RandomBoolStream1.C This program illustrates use of the pseudo-random bit generator of CoCoALib. The bits are independent, identically distributed; each with equal probability of being true or false. It is also possible to generate biased bits. See RandomLongStream & RandomBigIntStream if you want random integers.
CoCoALib offers a pseudorandom bit generator.  The generator can be   
seeded when it is created; this allows different pseudorandom         
sequences to be produced, though the sequence is completely determined
by the initial seed value.  The `prob' function filters a random bit  
sequence to produce `true' with a specified probability.              


ex-RandomLongStream1.C This program illustrates use of the pseudo-random number generator of CoCoALib. The numbers are independent and uniformly distributed in the given range; both ends of the range are reachable. See RandomBoolStream if you want random bools, & RandomZZStream if you want random large integers.
CoCoALib offers a way to make uniform pseudo-random number generators.      
When creating the generator you must specify the (inclusive) upper and lower
bounds for the random numbers which will be generated.  When creating a     
generator you may specify a `seed'; this allows different pseudo-random     
sequences to be produced, though the sequence is completely determined by   
its initial seed value.                                                     


ex-RandomZZStream1.C This program illustrates use of the pseudo-random number generator of CoCoALib. The numbers are independent and uniformly distributed in the given range; both ends of the range are reachable. See RandomBoolStream if you want random bools, & RandomLongStream if you want random machine integers.
CoCoALib offers a way to make uniform pseudo-random number generators.      
When creating the generator you must specify the (inclusive) upper and lower
bounds for the random numbers which will be generated.  When creating a     
generator you may specify a `seed'; this allows different pseudo-random     
sequences to be produced, though the sequence is completely determined by   
its initial seed value.                                                     


ex-ring1.C This example program shows how to use the rings ZZ and QQ, and how to perform various operations on ring elements (RingElem).
Use of the fundamental rings ZZ and QQ.                              
Creation of ring elements (C++ type RingElem).                       
Operations allowed on elements of the same ring:                     
  zero(R) and one(R)                                                 
  a + b, a - b, a * b                                                
  -a                                                                 
  a = b   (assignment)                                               
  a == b  and  a != b  (comparison)                                  
  IsZero(a), IsOne(a), IsMinusOne(a)                                 
Moreover other operations might be allowed, for example:             
  a > b   if the ring is ordered                                     
  a / b   if exact division is possible (and implemented!)           
See ex-RingHom*.C for how to move elements from one ring to another. 


ex-ring2.C This example program shows how to create various types of ring, and several operations one can perform on rings (e.g. querying their properties).
This example creates several different sorts of ring,            
and then calls PrintRingInfo on each one.                        
PrintRingInfo calls various functions to obtain information      
about each ring passed to it.  Naturally, some query functions   
make sense only for certain types of ring (e.g. NumIndets(R)).   


ex-RingElem1.C Example showing operations on RingElem for a ring or a PolyRing.
This is a long list of function calls from different rings.  


ex-RingFp1.C Inefficient program to compute sqrt(2) modulo a given number. Simple example using finite fields or integers modulo N.
The program asks the user for the value of N, it creates the     
ring of integers mod N, and finally uses "brute force" to find 
all square-roots of 2 modulo N.                                  


ex-RingFp2.C When computing over a finite field normally it is best to use the function NewZZmod to create the field. However, for the curious it is possible to create small prime finite fields stating the particular implemention method (there are 3 possibilities).
This program compares the speeds of computing sums and products in   
the three different implementations of small prime finite fields.    
It performs the timing tests for different sizes of prime, and       
illustrates that different implementations have different upper      
limits for the characteristic -- these limits depend on the platform.
It also gives the performance of the finite field created by NewZZmod


ex-RingHom1.C The example in this file shows how to create and use some homomorphisms between rings.
CanonicalHom is an easy way to make these homomorphisms:  
R --> R/I,    R --> R[x],   R --> FractionField(R),       
R --> R,      QQ --> R,     ZZ --> R,                     
PolyAlgebraHom makes the R-algebra homomorphisms:         
R[x] --> R,   R[x] --> R[y]                               


ex-RingHom2.C Operations between elements of different rings are not allowed but we can use homomorphisms to map the elements into the same ring.
The example in this file shows how to create and use some      
homomorphisms between rings.  In particular, it gives a simple 
example of mixed ring arithmetic: the user must map all values 
into a single ring before combining them arithmetically.       


ex-RingHom3.C This program shows how we define a ring homomorphism to perform a change of coordinates in a polynomial ring.
ex-RingHom4.C This program shows how we define a ring homomorphism to evaluate polynomials.
ex-RingHom5.C The example in this file shows how to create and use some homomorphisms between rings.
We compute these polynomials (with parameters) in some rings: 
f = (2*a/3-1)*x[0] + 1/a;  g = x[0]-a;                        


ex-RingQQ1.C Some simple computations with rational numbers. This example illustrates how to create the field of rational numbers. It shows that we can compute 7/3 in QQ but not in ZZ. It shows how to map an integer into a rational number.
Familiarize yourself with the example ex-RingZZ1.C before proceeding. 
As C++ does not natively have any rings, we must construct them from  
scratch.                                                              


ex-RingTwinFloat1.C Example showing some features of RingTwinFloat. Program to explore the precision offered by RingTwinFloat
ex-RingTwinFloat2.C Program exhibiting a way of using ever higher precisions... This example shows how failure can be a success: this pathological computation produces the same wrong result when using normal floating point arithmetic at any given finite precision! However, since twin floats are self-checking, we detect that there is a problem.
Example showing iterative increase of precision using RingTwinFloat    
until the answer is found (or some maximum precision is reached).      
This program will always fail to find the limit: J-M Muller's sequence 
actually converges to 6 (rather slowly), however it is pathological    
because it converges to 100 using any finite precision arithmetic.     
RingTwinFloat detects the onset of pathological convergence to 100, and
throws an InsufficientPrecision exception.                             


ex-RingTwinFloat3.C Program showing how some RingTwinFloat values can have more precision than that requested.
Example showing that certain RingTwinFloat values may have a precision  
higher than that requested.  In this case we request 64 bits (i.e.      
about 19 decimal digits), but in fact we can remove the nineteen most   
significant digits and still have a result with the requested precision.
So the original value of the variable third did in fact have at         
least 127 bits correct (i.e. about 38 decimal digits).                   


ex-RingWeyl1.C An example about RingWeyl, the interface is not quite settled yet.
All these examples about RingWeyl will probably be merged into one.


ex-RingWeyl2.C An example about RingWeyl, the interface is not quite settled yet.
This shows a computation of a Groebner Basis.
All these examples about RingWeyl will probably be merged into one.


ex-RingWeyl3.C An example about RingWeyl, the interface is not quite settled yet.
This shows a computation of a Groebner Basis.
All these examples about RingWeyl will probably be merged into one.


ex-RingWeyl4.C An example about RingWeyl, the interface is not quite settled yet.
This shows a computation of a Groebner Basis.
All these examples about RingWeyl will probably be merged into one.


ex-RingWeyl5.C An example about RingWeyl, the interface is not quite settled yet.
This shows a computation of a Groebner Basis.
All these examples about RingWeyl will probably be merged into one.


ex-RingZZ1.C This is a basic example about the creation and use of the ring of integers. It illustrates the CoCoALib "philosophy" of first creating a ring, and then computing with values in that ring. The C++ commands for performing arithmetic on RingElems have a natural syntax (except we cannot use ^ for powers). It warns about "mixed ring arithmetic", which is forbidden in CoCoALib.
To calculate with elements of a ring we must first create the   
ring, then we can create C++ objects of type RingElem which     
belong to the ring -- a RingElem can change its value but not   
the ring to which it belongs.                                   


ex-symbol1.C Creation of symbols, and some simple operations on them.
Symbols are used to give print names to indeterminates.  Their main   
use is as an argument to a pseudo-ctor for a PPMonoid or a polynomial 
ring -- see examples for those types.                                 


ex-symbol2.C This program shows simple use of the functions for creating new anonymous symbols.
Often algorithms need one to work with an addition new indeterminate
which must be different from all indeterminates already being use.  
In CoCoALib we can create new "anonymous" indeterminates guaranteed
to be different from all others.  This examples shows how to create 
them singly, and also several all together.