# Exact experiments for radical expressions in the roots of a general polynomial.
# Run with GAP 4 from the directory containing this file:
#     gap -q --quitonbreak root-expression-lab.g
# No optional GAP packages are required.
#
# To use the classifier with your own expression in an interactive session:
#     Read("root-expression-lab.g");;
#     x := List([1..5], i -> Indeterminate(Rationals, i));;
#     ClassifyRootExpression(x, 1 / (1 + Sum(x)));
#     ClassifyRootExpression(x, x[1] * x[2]);
# An accepted record returns symmetric A and B in the supplied variables.
# The article gives the separate conversion to elementary symmetric functions.

RootExpressionVandermonde := function(variables)
    return Product(Combinations([1..Length(variables)], 2),
                   pair -> variables[pair[2]] - variables[pair[1]]);
end;;

ClassifyRootExpression := function(roots, target)
    local n, rationalFamily, validVariable, ring, rename, j, cycle, image,
          oddImage, discriminantRoot;
    if not IsList(roots) then Error("Supply an ordered list of root variables."); fi;
    n := Length(roots);
    if n < 5 then return rec(status := "outside-degree", degree := n); fi;
    rationalFamily := FamilyObj(Indeterminate(Rationals, 1));
    validVariable := function(v)
        return FamilyObj(v) = rationalFamily and IsUnivariateRationalFunction(v)
               and not IsConstantRationalFunction(v)
               and v = Indeterminate(Rationals, IndeterminateNumberOfUnivariateRationalFunction(v));
    end;
    if not ForAll(roots, validVariable) or Length(Set(roots)) <> n then
        Error("The roots must be distinct indeterminates over the rationals.");
    fi;
    if IsRat(target) then return rec(status := "accepted", A := target, B := 0); fi;
    ring := PolynomialRing(Rationals, roots);
    if FamilyObj(target) <> rationalFamily or not IsRationalFunction(target)
       or not (NumeratorOfRationalFunction(target) in ring)
       or not (DenominatorOfRationalFunction(target) in ring) then
        Error("The target must be a rational function of the supplied roots over Q.");
    fi;
    rename := perm -> Value(target, roots, List([1..n], i -> roots[i^perm]));
    # The cycles (1,2,j) generate A_n. One unequal image rejects the target.
    for j in [3..n] do
        cycle := (1,2,j);
        image := rename(cycle);
        if target <> image then
            return rec(status := "rejected", cycle := cycle, image := image);
        fi;
    od;
    oddImage := rename((1,2));
    if target = oddImage then return rec(status := "accepted", A := target, B := 0); fi;
    discriminantRoot := RootExpressionVandermonde(roots);
    return rec(status := "accepted", A := (target + oddImage) / 2,
               B := (target - oddImage) / (2 * discriminantRoot));
end;;

RunRootExpressionLab := function()
    local require, threeCycles, commutator, searchPairs, exponentPatterns,
          monomial, firstSplit, testCandidates,
          n, report, split, witness, positive, negative;

    require := function(condition, message)
        if not condition then Error(message); fi;
    end;

    threeCycles := function(n)
        local cycles, triple, a, b, c;
        cycles := [];
        for triple in Combinations([1..n], 3) do
            a := triple[1]; b := triple[2]; c := triple[3];
            Add(cycles, (a,b,c));
            Add(cycles, (a,c,b));
        od;
        return cycles;
    end;

    # Mathematical products are read from right to left. GAP permutations act
    # on the right, so reverse the order to evaluate a b a^-1 b^-1.
    commutator := function(a, b)
        return b^-1 * a^-1 * b * a;
    end;

    searchPairs := function(n)
        local cycles, supports, counts, successes, first, i, j, overlap,
              result, lengths, types, number, neighbors;
        cycles := threeCycles(n);
        supports := List(cycles, MovedPoints);
        counts := [0, 0, 0, 0];
        successes := 0;
        first := fail;
        types := [[], [], [], []];
        for i in [1..Length(cycles)] do
            for j in [1..Length(cycles)] do
                overlap := Length(Intersection(supports[i], supports[j]));
                result := commutator(cycles[i], cycles[j]);
                lengths := SortedList(List(Cycles(result, MovedPoints(result)), Length));
                AddSet(types[overlap + 1], lengths);
                counts[overlap + 1] := counts[overlap + 1] + 1;
                if result = (1,2,3) then
                    successes := successes + 1;
                    if first = fail then first := [cycles[i], cycles[j]]; fi;
                fi;
            od;
        od;
        number := 2 * Binomial(n, 3);
        # For a fixed first support, choose the shared labels and remaining
        # labels of the second support, then one of its two orientations.
        neighbors := List([0..3], k -> 2 * Binomial(3,k) * Binomial(n-3,3-k));
        require(counts = number * neighbors, "Pair counts failed.");
        require(successes * number = counts[2], "Witness count failed.");
        return rec(counts := counts, types := types, successes := successes,
                   first := first);
    end;

    # Sorting an exponent vector picks one representative of its S_n orbit.
    # Integer partitions give precisely the sorted exponent vectors, with
    # leading zeroes added to obtain length n.
    exponentPatterns := function(n, degree)
        local partitions;
        if degree = 0 then return [List([1..n], i -> 0)]; fi;
        partitions := Filtered(Partitions(degree), p -> Length(p) <= n);
        return List(partitions, p ->
            Concatenation(List([1..n-Length(p)], i -> 0), SortedList(p)));
    end;

    monomial := function(variables, exponents)
        return Product([1..Length(variables)], i -> variables[i]^exponents[i]);
    end;

    firstSplit := function(n)
        local even, odd, degree, pattern, tested, oddImage, evenOrbit, oddOrbit,
              variables, positive, negative;
        even := Elements(AlternatingGroup(n));
        odd := List(even, p -> p * (1,2));
        tested := 0;
        degree := 0;
        while true do
            for pattern in exponentPatterns(n, degree) do
                tested := tested + 1;
                # The even and odd images are two A_n orbits. They coincide
                # if one odd image belongs to the even orbit, and otherwise
                # are disjoint. This membership test actually searches A_n.
                oddImage := Permuted(pattern, (1,2));
                if not ForAny(even, p -> Permuted(pattern, p) = oddImage) then
                    evenOrbit := Set(even, p -> Permuted(pattern, p));
                    oddOrbit := Set(odd, p -> Permuted(pattern, p));
                    require(Intersection(evenOrbit, oddOrbit) = [],
                            "The two reported orbits intersect.");
                    require(degree = Binomial(n, 2) and pattern = [0..n-1],
                            "Unexpected first split.");
                    require(Length(evenOrbit) = Factorial(n) / 2 and
                            Length(oddOrbit) = Factorial(n) / 2,
                            "Unexpected sizes of the first split orbits.");
                    variables := List([1..n], i -> Indeterminate(Rationals, i));
                    positive := Sum(evenOrbit, p -> monomial(variables, p));
                    negative := Sum(oddOrbit, p -> monomial(variables, p));
                    require(positive - negative = RootExpressionVandermonde(variables),
                            "The signed orbit sum is not the Vandermonde.");
                    return rec(degree := degree, pattern := pattern,
                               size := Length(evenOrbit), tested := tested,
                               positive := positive, negative := negative);
                fi;
            od;
            degree := degree + 1;
        od;
    end;

    testCandidates := function(positive, negative)
        local variables, alternate, accepted, partner, candidate, rejected,
              denominator, fraction, rationalResult, reciprocalNorm, reciprocal;
        variables := List([1..5], i -> Indeterminate(Rationals, i));
        alternate := RootExpressionVandermonde(variables);
        accepted := ClassifyRootExpression(variables, alternate);
        require(accepted.status = "accepted" and IsZero(accepted.A) and
                IsOne(accepted.B), "Vandermonde classification failed.");
        # Each input is a raw sum of 60 individually relabeled monomials.
        accepted := ClassifyRootExpression(variables, positive);
        partner := ClassifyRootExpression(variables, negative);
        require(accepted.status = "accepted" and partner.status = "accepted" and
                accepted.A = partner.A and accepted.B = -partner.B and
                IsOne(2 * accepted.B) and positive = accepted.A + accepted.B * alternate,
                "Two-term reconstruction failed.");
        require(ForAll(GeneratorsOfGroup(SymmetricGroup(5)),
                       q -> Value(accepted.A, variables,
                                  List([1..5], i -> variables[i^q])) = accepted.A),
                "The symmetric component is not symmetric.");
        Print("Accepted: D has (A,B) = (0,1).\n");
        Print("The even and odd 60-term sums have the same A and B = +1/2 or -1/2.\n");
        # E = positive, O = negative, and E - O = D.
        # Multiplying 1/(1+E) by (1+O)/(1+O) gives a symmetric denominator.
        reciprocalNorm := (1 + positive) * (1 + negative);
        reciprocal := ClassifyRootExpression(variables, 1 / (1 + positive));
        require(reciprocal.status = "accepted" and
                2 * reciprocalNorm * reciprocal.A = 2 + positive + negative and
                IsOne(-2 * reciprocalNorm * reciprocal.B),
                "Reciprocal of the even orbit sum plus one failed.");
        Print("For 1/(1+E), N = (1+E)(1+O).\n");
        Print("The classifier gives A = (2+E+O)/(2N) and B = -1/(2N).\n");
        candidate := variables[1]*variables[2] + variables[3]*variables[4];
        rejected := ClassifyRootExpression(variables, candidate);
        require(rejected.status = "rejected" and rejected.cycle = (1,2,3) and
                rejected.image = variables[2]*variables[3] + variables[1]*variables[4],
                "The rejecting certificate is incorrect.");
        Print("Rejected: ", candidate, " changes to ", rejected.image,
              " under ", rejected.cycle, ".\n");
        denominator := 1 + Sum(variables);
        require(ClassifyRootExpression(variables, 1 / denominator) =
                    rec(status := "accepted", A := 1 / denominator, B := 0) and
                ClassifyRootExpression(variables, variables[1]*variables[2]) =
                    rec(status := "rejected", cycle := (1,2,3), image := variables[2]*variables[3]),
                "The introductory classifier examples failed.");
        fraction := (1 + alternate) / denominator;
        rationalResult := ClassifyRootExpression(variables, fraction);
        require(rationalResult.status = "accepted" and
                IsOne(rationalResult.A * denominator) and
                IsOne(rationalResult.B * denominator),
                "Rational-function reconstruction failed.");
        require(ClassifyRootExpression(variables, variables[1] / denominator).status = "rejected"
                and ClassifyRootExpression(variables, 2/7) = rec(status := "accepted", A := 2/7, B := 0)
                and ClassifyRootExpression(variables{[1..4]}, variables[1]).status = "outside-degree",
                "The rational, constant, or degree-bound checks failed.");
        Print("Accepted: (1+D)/(1+sum of roots) has A = B = 1/(1+sum of roots).\n");
    end;

    Print("Ordered pairs of three-cycles, counted by shared labels\n");
    Print("n  counts for overlap 0,1,2,3  pairs giving (1,2,3)\n");
    for n in [3..9] do
        report := searchPairs(n);
        Print(n, "  ", report.counts, "  ", report.successes, "\n");
        if n = 5 then witness := report.first; fi;
    od;
    require(report.types = [[[]], [[3]], [[2,2]], [[]]],
            "Unexpected commutator cycle types.");
    Print("Observed nontrivial cycle lengths by overlap: ",
          List(report.types, outcomes -> outcomes[1]), ".\n");
    require(witness <> fail, "The five-label search returned no witness.");
    Print("First five-label witness: [", witness[1], ",", witness[2],
          "] = ", commutator(witness[1], witness[2]), " (right-to-left).\n\n");

    Print("First degree where a monomial orbit splits for A_n\n");
    Print("n  degree  exponents  size of each orbit  patterns examined\n");
    for n in [3..6] do
        split := firstSplit(n);
        Print(n, "  ", split.degree, "  ", split.pattern, "  ",
              split.size, "  ", split.tested, "\n");
        if n = 5 then positive := split.positive; negative := split.negative; fi;
    od;
    Print("In each degree the signed orbit sum equals D as a formal polynomial.\n\n");
    testCandidates(positive, negative);
    Print("All exact checks passed.\n");
end;

RunRootExpressionLab();

# Exact even and odd sums for x2*x3^2*x4^3*x5^k at the roots of X^5-4X+2.
# After Read, try FixedQuinticOrbitData(6); or FixedQuinticOrbitData(8);
# The matrix multiplies by X in the basis 1, X, X^2, X^3, X^4 modulo f.
FixedQuinticCompanion := Immutable([[0,0,0,0,-2], [1,0,0,0,4], [0,1,0,0,0],
                                    [0,0,1,0,0], [0,0,0,1,0]]);;

# I(a,b,...) sums over distinct root indices. Multiplying p_a by I(b,...)
# includes the cases where the first index equals one of the later indices.
FixedQuinticInjectiveSum := function(exponents, powerSum)
    local first, rest, result, position, merged;
    if IsEmpty(exponents) then return 1; fi;
    first := exponents[1];
    rest := exponents{[2..Length(exponents)]};
    result := powerSum(first) * FixedQuinticInjectiveSum(rest, powerSum);
    for position in [1..Length(rest)] do
        merged := ShallowCopy(rest);
        merged[position] := merged[position] + first;
        result := result - FixedQuinticInjectiveSum(merged, powerSum);
    od;
    return result;
end;;

FixedQuinticOrbitData := function(k)
    local powerSum;
    if not IsInt(k) or k < 0 then Error("The exponent must be a nonnegative integer."); fi;
    powerSum := j -> TraceMat(FixedQuinticCompanion^j);
    # Four distinct indices determine the fifth, which carries exponent zero.
    # Column 1 of M^k represents X^k mod f. In the alternating determinant
    # the first four rows already represent 1,X,X^2,X^3, so only row 5's
    # coefficient of X^4 contributes. Thus E_k - O_k = coefficient * D.
    return rec(total := FixedQuinticInjectiveSum([1,2,3,k], powerSum),
               coefficient := (FixedQuinticCompanion^k)[5][1]);
end;;

CheckFixedQuinticOrbitSums := function()
    local require, companion, identity, powerSums, injectiveSum, sampleSums,
          allSum, polarizedSum, gram, derivative, discriminant, atFiveEighths,
          orbitProduct, data, k, current, fourBack, fiveBack, crossGram,
          traceTable, exceptions, commonValues, shiftedMean, reciprocalNorm,
          reciprocalA, reciprocalB;

    require := function(condition, message)
        if not condition then Error(message); fi;
    end;
    companion := FixedQuinticCompanion;
    identity := IdentityMat(5);
    require(companion^5 = 4 * companion - 2 * identity, "Companion relation failed.");
    powerSums := List([0..10], k -> TraceMat(companion^k));
    require(powerSums = [5,0,0,0,16,-10,0,0,64,-72,20], "Power sums failed.");

    injectiveSum := exponents -> FixedQuinticInjectiveSum(exponents, j -> powerSums[j+1]);
    sampleSums := List([[3,3,4], [2,4,4], [2,3,5]], injectiveSum);
    require(sampleSums = [40,40,-60], "Distinct-index triples failed.");
    allSum := injectiveSum([0,1,2,3,4]);
    require(allSum = -20 and allSum = injectiveSum([1,2,3,4]), "Full orbit sum failed.");

    # det(sum_j y_j M^(a_j)) = product_i(sum_j y_j x_i^(a_j)).
    # Inclusion-exclusion extracts the coefficient of y_1*...*y_5.
    # Subsets are of the five positions, even when two exponents coincide.
    polarizedSum := function(k)
        local powers, total, subset, matrixSum, j;
        powers := List([0,1,2,3,k], exponent -> companion^exponent);
        total := 0;
        for subset in Combinations([1..5]) do
            matrixSum := 0 * identity;
            for j in subset do matrixSum := matrixSum + powers[j]; od;
            total := total + (-1)^(5-Length(subset)) * DeterminantMat(matrixSum);
        od;
        return total;
    end;

    # The even sum minus the odd sum is the Vandermonde determinant.
    # Its square is det(p_(i+j)), also the product of f'(x_i) in degree 5.
    gram := List([0..4], i -> List([0..4], j -> powerSums[i+j+1]));
    derivative := 5 * companion^4 - 4 * identity;
    require(companion * derivative = 16 * companion - 10 * identity, "X f'(X) reduction failed.");
    atFiveEighths := (5/8)^5 - 4 * (5/8) + 2;
    discriminant := DeterminantMat(gram);
    require(discriminant = DeterminantMat(derivative) and
            discriminant = 16^5 * atFiveEighths / 2 and
            discriminant = -16 * 13259, "Discriminant failed.");
    orbitProduct := (allSum^2 - discriminant) / 4;
    require(orbitProduct = 53136 and discriminant = -212144, "Orbit quadratic failed.");
    Print("p_0,...,p_10 = ", powerSums, "\n");
    Print("I(3,3,4), I(2,4,4), I(2,3,5) = ", sampleSums, "\n");
    Print("E + O = ", allSum, "; (E - O)^2 = ", discriminant, "\n");
    Print("Orbit quadratic: t^2 + 20*t + ", orbitProduct,
          ". Values: -10 +/- 2*sqrt(-13259).\n");

    # 1+E = shiftedMean + D/2 and 1+O = shiftedMean - D/2.
    shiftedMean := 1 + allSum / 2;
    reciprocalNorm := 1 + allSum + orbitProduct;
    reciprocalA := shiftedMean / reciprocalNorm;
    reciprocalB := -1 / (2 * reciprocalNorm);
    require(reciprocalNorm = 53117 and reciprocalA = -9/53117 and
            reciprocalB = -1/106234, "Reciprocal coefficients failed.");
    # Verify the constant and D coefficients of (1+E)(A+B*D) = 1.
    require(shiftedMean * reciprocalA + discriminant * reciprocalB / 2 = 1 and
            shiftedMean * reciprocalB + reciprocalA / 2 = 0,
            "The reciprocal does not multiply back to one.");
    Print("(1+E)(1+O) = ", reciprocalNorm, ". In 1/(1+E) = A+B*D,\n");
    Print("A = ", reciprocalA, " and B = ", reciprocalB, ".\n");

    # Each root satisfies x^k = 4*x^(k-4) - 2*x^(k-5) for k >= 5.
    # Linearity gives the same recurrence for the total and the coefficient.
    data := List([0..60], FixedQuinticOrbitData);
    require(List(data{[1..5]}, row -> row.total) = [0,0,-128,112,-20] and
            List(data{[1..5]}, row -> row.coefficient) = [0,0,0,0,1],
            "Initial exponent data failed.");
    for k in [5..60] do
        current := data[k+1];
        fourBack := data[k-4+1]; fiveBack := data[k-5+1];
        require(current.total = 4*fourBack.total - 2*fiveBack.total and
                current.coefficient = 4*fourBack.coefficient - 2*fiveBack.coefficient,
                "Exponent recurrence failed.");
    od;
    Print("k    E_k + O_k    c_k in E_k - O_k = c_k*D\n");
    for k in [4..9] do
        current := data[k+1];
        require(polarizedSum(k) = current.total, "Determinant polarization failed.");
        Print(k, "    ", current.total, "    ", current.coefficient, "\n");
    od;
    # Independently check the signed coefficient by multiplying the two
    # evaluation matrices, with exponent lists (0,1,2,3,k) and (0,1,2,3,4).
    # Their product after transposing the second has entries p_(i+j),
    # and determinant (E_k-O_k)*D = c_k*discriminant.
    traceTable := List([0..64], j -> TraceMat(companion^j));
    for k in [4..60] do
        crossGram := List([0,1,2,3,k], i -> List([0..4], j -> traceTable[i+j+1]));
        require(DeterminantMat(crossGram) = data[k+1].coefficient * discriminant,
                "Signed determinant check failed.");
    od;
    exceptions := Filtered([4..60], k -> data[k+1].coefficient = 0);
    require(exceptions = [5,6,7,10,11,15], "Unexpected equal sums through k=60.");
    commonValues := List(exceptions, k -> polarizedSum(k)/2);
    require(commonValues = [0,-256,352,-1024,1920,9728]
            and commonValues = List(exceptions, k -> data[k+1].total/2),
            "Independent equal-sum values failed.");
    Print("Equal sums through k=60 at ", exceptions, ".\n");
    Print("Their common values are ", commonValues, ".\n");
end;;

CheckFixedQuinticOrbitSums();
