-- In this tutorial we describe one way to represent
-- divisors on a smooth projective subvariety 
-- $X$ of $\PP^r$, and show methods for computing
-- the group operations, computing the vector space
-- of sections, and determining whether two divisors are
-- linearly equivalent.  We also construct the
-- canonical divisor on $X$.
--
-- We consider smooth varieties only, although most
-- of this can be extended to normal varieties.
-- Cartier and Weil divisors on normal varieties
-- might be the subject of a further tutorial.
--
-- Other possible future topics would be:
-- intersection numbers, determining whether a divisor
-- is very ample, and finding the base point locus of
-- the divisor class.
--
-- The simplest case is when the homogeneous coordinate
-- ring $S_X$ of $X$ satisfies the $S_2$ condition of Serre:
-- We say that a domain $R$ is $S_2$ if 
-- every proper nonzero principal ideal
-- has pure codimension 1 (all associated
-- primes of the ideal are of codimension 1).
--
-- In this tutorial, we consider the case when this
-- holds (e.g., this holds for complete intersections).
-- In a further tutorial, we will make the necessary
-- extensions to handle the non $S_2$-case.
--
-- An example that we will use throughout is the plane
-- cubic curve $E$, whose homogeneous coordinate ring is {\tt SE}:

KK = ZZ/31991
SE = KK[x,y,z]/(y^2*z - x*(x-z)*(x+3*z))

-- The sections in this tutorial are
-- 
-- A. Representation of divisors
--
-- B. Group operations on divisors
--
-- C. Global Sections
--
-- D. Linear Equivalence
--
-- E. The canonical divisor

--------------------------------
-- A. Representation of divisors
--------------------------------
-- Let $X$ be a smooth irreducible
-- variety.  A (Weil) divisor on
-- $X$ is an integral linear combination of irreducible
-- subvarieties of $X$ of codimension $1$. The divisor
-- is called effective if all the coefficients
-- are non-negative.  To any ideal $I$ in the homogeneous
-- coordinate ring $S_X$ of $X$ we associate the 
-- effective divisor that is the sum of the
-- pure codimension $1$ components of $I$, each
-- taken with the multiplicity it has in the
-- primary decomposition of $I$.
--
-- Let $D = E - F$
-- be a divisor, where $E$ and $F$ are effective.
-- Because $X$ is normal, there is a unique 
-- homogeneous ideal $I$ in $S_X$
-- such that $V(I) = E$, and $I$ is either $(1)$, or has
-- pure codimension one.  Similarly, there is a unique
-- such ideal $J$ with $V(J) = F$.
-- Our plan is to represent the divisor $D$ by the pair
-- of ideals $(I,J)$.
--
-- This representation is not unique.  If $(I,J)$ and
-- $(I',J')$ are two pairs of ideals (such that each ideal 
-- is either $(1)$ or has pure codimension one), then
-- $(I,J)$ and $(I',J')$ represent the same divisor iff
--    $$sat(I J') = sat(I' J),$$ 
-- where $sat(K)$ is the saturation of $K$ (the largest
-- ideal $L$ such that a power of the irrelevant ideal
-- times $L$ is in $K$)
-- Write $(I,J) \equiv (I',J')$ if $sat(I J') = sat(I' J)$.
--
-- This correspondence defines a bijection between
-- $Div(X)$ and $\{(I,J) \mid I,J$ are homogeneous ideals in $S_X$
--                either trivial, or pure codim one$\}/\equiv$.
--
-- As we will often have to saturate ideals of
-- codimension 1, we give here the most efficient
-- method we know, which has the additional 
-- advantage of throwing away all components
-- not of codimension 1.  That is, we define
-- {\tt purify1S2(I)}, a function that takes an arbitrary
-- ideal $I$ in a ring satisfying $S_2$, and returns
-- the ideal which is the intersection of the
-- codimension 1 primary components of $I$.
-- In the next divisor tutorial (not yet written),
-- we will write a routine {\tt purify1(I)} which does
-- not require the ring to be $S_2$.

--^
purify1S2 = I -> (
    -- Assuming ring I is S2, and I is not 0, returns the 
    -- pure codimension 1 part of I.
    -- Find a nonzero element of I:
    M := compress gens I;
    -- Explanation: gens I is 
    -- the matrix of generators of I; compress
    -- removes the entries that are 0
    -- and := makes M a local variable.
    if numgens source M == 0 
    then error "purify1S2: expected nonzero ideal";
    f := ideal M_(0,0);
    -- f is the ideal generated by the first entry.
    -- Since ring I is S2, the ideal f is 
    -- pure codimension 1.  Thus
    f:(f:I)
    -- is the pure codimension 1 part. (The last 
    -- expression given in a function is the returned
    -- value, provided the semicolon is left off.)
    )
--$
-- For example, in the ring
R = ZZ/5[a,b]
-- we have
purify1S2 ideal(a^2,a*b)

--B Unfortunately at this moment the quotient code
--B makes this slow.  Another possibility is
--B purify1S2 = saturation 
--B which is (9/23/96) slightly faster (88 vs 106 sec).
--
-- Throughout this tutorial, we will treat divisors
-- as equivalence classes of pairs, and our operations
-- will operate on pairs.  So let's define a 
-- divisor type in Macaulay2. The following declaration
-- provides a new data type, the {\tt Divisor}.

Divisor = new Type of BasicList

-- Let's write a routine to create a divisor, from
-- either a single ideal, or a pair of ideals.
-- (This routine should check that its arguments are
-- pure codimension one, or trivial, and in the same ring,
-- but we will ignore that).
--
-- Defining {\tt divisor} to be a method allows us to define
-- different versions of this routine which take different
-- arguments.

divisor = method()

-- The following allows us to define an object of
-- class {\tt Divisor} from a pair of ideals.

divisor(Ideal,Ideal) := (I,J) -> new Divisor from {purify1S2 I,purify1S2 J};

-- The following routine defines an (effective)
-- divisor from a single ideal.

divisor Ideal := I -> divisor(I, ideal 1_(ring I));

-- The divisors of some rational points on the
-- elliptic curve $E$ include

P = divisor ideal(x,z)
R = divisor ideal(x,y)
R1 = divisor ideal(x-z,y)
R2 = divisor ideal(x+3*z,y)
Q1 = divisor ideal(y-6*z, x-3*z)

-- Testing equality of divisors is often made simpler
-- by having a ``normal form'' for divisors.
-- The normal form of a divisor $D$ is $E - F$ where
-- $E$ and $F$ are both effective and have disjoint support.
-- It is easy to see that the normal form of $(I,J)$ is
-- $(I:J, J:I)$.
--
-- In the following code, the expressions
-- {\tt D\#0} and {\tt D\#1} refer to the first and second ideals
-- in the list representing $D$. ({\tt D\#0} is the first 
-- because Macaulay2 counts everything starting from 0.)
normalForm = method()
normalForm Divisor := D -> new Divisor from {D#0 : D#1, D#1 : D#0};
-- Two pairs $(I,J), (I',J')$ define the same divisor
-- exactly when their normal forms are equal.
-- The following code establishes a method for testing
-- the equality of divisors.  The function "toList" converts
-- a divisor to a list of ideals, and then we let the built
-- in method for comparing lists take over: it compares corresponding
-- elements.
--^
Divisor == Divisor := (D,E) -> toList normalForm D == toList normalForm E;
--$
-- An important point here is that the built in method for comparing
-- two ideals used by the operator "==" succeeds even if the 
-- given generators differ.

-- We shall later show that with {\tt R1} and {\tt R2} as
-- above, the divisor {\tt (R1 + R2) - R1} is represented by

D = divisor(ideal(y, x^2+2*x*z-3*z^2), ideal(x-z, y))

-- so that the normal form of $D$ is {\tt R2}:

normalForm D

-- and we can directly test equality by

D == R2

----------------------------------
-- B. Group operations on divisors
----------------------------------
-- To add divisors we multiply the corresponding
-- ideals and then saturate.
-- This may be coded as follows
-- (the products are saturated in the {\tt divisor} routine):

--^
Divisor + Divisor := (D,E) -> divisor(D#0 * E#0, D#1 * E#1);
--$
-- Negation is even simpler, since all we need do
-- is exchange the two ideals.  We don't use the
-- {\tt divisor} routine, since our ideals are already
-- saturated.

- Divisor := (D) -> new Divisor from {D#1, D#0};

-- Let's also include functions to compute differences
-- and to multiply by integers.

Divisor - Divisor := (D,E) -> D + (-E);

--^
ZZ Divisor := ZZ * Divisor := (n,D) -> divisor((D#0)^n, (D#1)^n);
--$
-- Some arithmetic of divisors on our elliptic curve

2 P

3 P

-- Notice that $3P$ is the hyperplane section $z=0$,
-- which is the equation of the flex line to the
-- cubic at the point $P$.

D = P-R1

D2 = 2 P - 2 R1

------------------------
-- C. Global Sections
------------------------
-- Since we have assumed $X$ smooth, Weil divisors can
-- all be represented by Cartier divisors, that is, 
-- by sections of an invertible sheaf.  If $D = (I,J)$
-- is a divisor, and $sheaf(I)$ denotes the sheaf of 
-- $O_X$-modules corresponding to $I$, then we put
-- $$O_X(D) = sheaf(I)^{-1} \otimes sheaf(J).$$
--
-- We define $L(D)$ to be the space of
-- global sections of the sheaf $O_X(D)$. Note that
-- a global section is the same as a 
-- sheaf homomorphism $O_X \rightarrow{} O_X(D)$.
-- If we write $D = E-F$, where $E$ and $F$ are effective,
-- then global sections
-- of $O_X(E-F)$ can be identified with homomorphisms
-- $O_X(-E) \rightarrow{} O_X(-F)$.
--
-- If we write $D = (I,J)$, then 
-- $L(D)$ and $Hom(I,J)$ can be identified with
-- subsets of the field of fractions of $S_X$.  
-- Since $S_X$ satisfies $S_2$, these sets are equal.
-- The following proposition allows us to compute $Hom(I,J)$:
-- 
-- {\bf Proposition}. Suppose $X$ is a smooth projective variety
-- whose homogeneous coordinate ring $S_X$ is $S_2$.
-- If $D$ is the divisor $(I,J)$ and
-- $f$ is any non-zero element of $I$, then
-- $L(D)$ is the degree zero part of  
-- $${sat((f*J) : I) \over f}.$$
--
--
-- {\bf Proposition}. If $s = g/f$ is section of the divisor
-- $D = (I,J)$ as above, then
-- the zero scheme of $s$ is defined by the ideal
--             $$ sat(f I : g) : J.$$
--
--
-- Consider the divisor $2P$ on our curve $E$:
D = 2 P
-- In this case, $I = (x^2, z)$, and $J = (1)$.
-- Compute the vector space of sections $L(2P)$:

I = D#0
J = D#1
f = z

-- The degree 0 part in the proposition is the
-- degree $d$ part of $sat((fJ) : I)$, divided by $f$,
-- where $d = deg f$.
--
-- We can use the command {\tt basis} to obtain a vector
-- space basis of a module or ideal in a given degree
-- and thus compute the global sections
-- (For an explanation of this use of the {\tt basis}
-- routine, see the tutorial on canonical embeddings
-- of plane curves and gonality)

LD = basis(degree f, purify1S2((f*J) : I))
LD = super (LD ** (ring target LD))

-- so the vector space $L(2P)$ 
-- is generated by $1=z/z$, and $x/z$.
-- Since $J = (1)$, the zero locus of the section 
-- $(z+x)/z$ is defined by the ideal

imI = purify1S2(((z+x)*I) : z)

-- and its degree is:
degree imI

-- Let's now package this into a routine
-- {\tt globalSections} which takes an argument {\tt D} of class
-- {\tt Divisor}, and 
-- computes a basis of $L(D)$, represented as
-- fractions with a common denominator.
-- The output is a row vector of the numerators, 
-- followed by the denominator.

globalSections = method()
--^
globalSections Divisor := (D) -> (
    -- First let's grab the parts (I,J) of D.
    I := D#0;
    J := D#1;
    -- Let 'f' be the first element of the 
    -- matrix of generators of the ideal I.
    f := (gens I)_(0,0);
    -- Now compute the basis of global sections
    -- just as above
    LD := basis(degree f, purify1S2((f*J) : I));
    LD = super (LD ** (ring target LD));
    -- Return both this vector space and the denominator
    {LD, f});
--$
-- Another important task is to
-- find the ideal of zeros of a section $s = f/g$
-- of a divisor $D$.

--^
sectionIdeal = (f,g,D) -> (
    I := D#0;
    J := D#1;
    purify1S2((f*I):g) : J
    );
--$
-- Let's find the image of the elliptic curve $E$
-- under the linear system $4P$. To do this we
-- define a ring homomorphism from the global
-- sections with the command
-- map. Its kernel defines the image of $E$.

D = 4 P
L = globalSections D
phi = map(SE, ZZ/31991[a..d], L#0)
ker phi

-- The image in $\PP^3$ is a complete intersection of two
-- quadrics: the elliptic normal curve in $\PP^3$.
--
-- For a less obvious example, consider
-- the divisor $4P - R$, which is not effective.
-- Since it has degree 3 as a divisor on an elliptic
-- curve, the Riemann Roch theorem tells us that
-- it is equivalent to an effective divisor; in
-- fact that it has  three sections. We can check
-- this as follows:

D = 4 P - R
L = globalSections D
II = sectionIdeal(y*z+x*z+x^2, z^2, D)
degree II

------------------------
-- D. Linear Equivalence
------------------------

-- Testing whether two divisors $E$ and $F$ are
-- linearly equivalent boils down to testing
-- whether $D = E-F$ is principal and thus
-- linearly equivalent to 0.
--
-- One method to determine whether $D$ is principal
-- is to compute the global sections of $D$.
-- A divisor $D$ is principal iff
-- $L(D)$ has dimension one, and the
-- zero locus of its generator is the empty set.
--
-- For example, on the elliptic curve $E$,
-- consider $P - R$:

globalSections (P-R)

-- $P-R$ has no global sections, so it is not equivalent
-- to 0.

-- Now consider $2 P - 2 R$

D = 2 P - 2 R

LB = globalSections D

-- Since the divisor $D = 2P-2R$ has degree 0 and has a
-- section, $D$ is linearly equivalent to 0.
-- The result shows that the
-- rational function $x/z$ has divisor $2P-2R$.
--
-- To check that a divisor of unknown degree
-- is equivalent to 0, we attempt to find a section
-- and show it does not vanish anywhere.  
-- We include this in the routine below.
--
-- Remember that in this tutorial
-- we are assuming that $S_X$ is $S_2$ and that $X$
-- is smooth.  These computations are easily modified
-- in the non-$S_2$ case.  See the corresponding tutorial,
-- once it is written!

--^
linearlyEquivalent = (D,E) -> (
    F := normalForm(D-E);
    LB := globalSections F;
    L := LB#0;
    -- L is the matrix of numerators. Thus numgens source L
    -- is the dimension of the space of global sections.
    if numgens source L != 1 
    then false
    else (
        R := ring L;
        V := sectionIdeal(L_(0,0), LB#1, F);
        if V == ideal(1_R) 
          then L_(0,0)/LB#1
          else false)
    );
--$
-- We get the same answers as before:
linearlyEquivalent(P,R)
linearlyEquivalent(2 P, 2 R)

-- We now look at the group law on the cubic:
-- We take the point $P$ to be 0; we can then
-- identify the natural group of divisor classes
-- of degree 0 with the set of points on the curve.
-- With this identification, 
-- the group law $++$ on points of the curve
-- is defined by: $R ++ S =$
-- the unique point $T$ for which the divisor
-- $(R-P)+(S-P)$ is
-- linearly equivalent to $(T-P)$.
-- i.e. $R ++ S := $ unique effective divisor in $R+S-P$.
--
-- What we need to do is: given a divisor $R+S-P$, find
-- an effective divisor equivalent to it.

--^
effective = (D) -> (
    LB := globalSections D;
    L := LB#0;  -- the matrix of numerators
    if numgens source L == 0 
    then error(toString D + " is not effective")
    else divisor sectionIdeal(L_(0,0), LB#1, D));
--$
effective(2 R - P)
addition = (R,S) -> effective(R + S - P);
addition(R1,R2)

-- Some points are in the torsion subgroup:

Q2 = addition(Q1, Q1)
Q3 = addition(Q2, Q1)
Q4 = addition(Q3, Q1)
Q4a = addition(Q2,Q2)

-- So the point $Q_1 = (3,6,1)$ is a point of order 4
-- in the group.
--
-- Exercise:  Write a routine that computes 
-- $n$ times a point in this group law.

---------------------------
-- E. The canonical divisor
---------------------------
--
-- The most important 
-- divisor class on a variety is the
-- canonical class.
-- For example, consider the 
-- twisted cubic curve whose ideal is the
-- ideal of $2\times 2$ minors of the ``catalecticant''
-- matrix 
S = ZZ/31991[a,b,c,d];
catalect = map(S^2, 3, (i,j)->S_(i+j))
IC = minors(2, catalect)
SX = S/IC

-- As a graded module, the 
-- canonical class is given
-- as $K_X = Ext^c(S_X, S(-r-1))$,
-- where $c = codim X$, 
-- $X \subset \PP^r$, and $S = k[x_0,\ldots,x_r]$
-- is the polynomial ring.

KX = Ext^2(coker gens IC,S^{-4})
canpres = substitute(presentation(KX), SX)
betti canpres

-- Thus we need a routine that takes a 
-- rank 1 torsion free module over a domain
-- and finds an ideal isomorphic to it.
-- We wish to compute homomorphisms from
-- the canonical module into $S_X$, and take
-- the divisor whose first ideal is the
-- image of a homomorphism of non-negative
-- degree, and whose second ideal is an
-- arbitrary nonzero element of $S_X$ whose
-- degree is equal to the degree of the
-- homomorphism.

-- First we find a homomorphism of lowest 
-- degree:

I1 = transpose (syz transpose canpres)_{0}
-- The degree is
dg = (degrees (target I1))_0_0

-- We need to balance the degree {\tt dg} with a power
-- of the first nonzero generator of the ring.
-- This is done in the following packaged version.

--^
divisorFromModule = M -> (
  -- given a module M, returns the divisor of the image
  -- of a nonzero homomorphism to R, suitably twisted.
  -- first get the presentation of M
    I1 := transpose (syz transpose presentation M)_{0};
  -- The degree is
    d := (degrees target I1)_0_0;
  -- We need to balance the degree d with a power
  -- of the first nonzero generator of the ring.
    var1 := (compress vars ring M)_{0};
  -- Now fix up the degrees.
    if d==0 then divisor ideal I1
    else if d>0 then divisor(
                  ideal (I1**dual(target I1)),
                  ideal var1^d
                 )                          
    else divisor ideal( 
               var1^(-d)**I1**dual target I1
               )
);
--$
-- We start from a module over the ring {\tt SX}:
M = coker canpres
divisorFromModule M

-- Some tests: 
use SX
divisorFromModule image matrix{{d^2}}
divisorFromModule SX^{1}

-- Here is the canonical divisor routine in packaged
-- form:

--^
canonicalDivisor= SX ->(
  -- Given a ring SX, computes a canonical divisor for SX
  I := ideal presentation SX;
  S := ring I;
  embcodim := codim I;
  M := Ext^embcodim(coker gens I,S^{-numgens S});
  M = coker substitute(presentation M, SX);
  divisorFromModule M
  );
--$
--
canonicalDivisor SX

-- There are other 
-- ways of computing the canonical
-- class. Perhaps we have already written a
-- tutorial on this subject.
