diff --git a/BREAKING-CHANGES.md b/BREAKING-CHANGES.md
index e4ccd9325..235a564f3 100644
--- a/BREAKING-CHANGES.md
+++ b/BREAKING-CHANGES.md
@@ -481,6 +481,34 @@ before v3, which decides exact comparisons exactly (#1019 §10). Two decimals th
| `sqrt(5)^1000 = 5^500` | `False` | stays written |
| `sqrt(2) < sqrt(2) + 10^(-150)` | `False` | stays written |
+### A rational function in nine to sixteen variables has a canonical form
+
+**Silent: a sum of fractions is gathered and cancelled whatever its variables are called.** A monomial held eight
+variables, so `Transformation.RationalCanonicalization` had no answer for an expression with nine. `Simplify` then
+had only rules that meet two terms where the names sort them side by side, and its answer depended on a variable's
+name. A monomial holds sixteen variables now, and the canonical form reads that many. Seventeen or more are still
+refused. The solvers, the integrator and the evaluator still read at most eight. Measured on master
+(`2a7247653`) and on this branch ([#2721](https://github.com/asc-community/AngouriMath/issues/2721)).
+
+With `D = a^2 * (m + n) * n - (a * c * n)^2` and `E = n / D * (n * w^2 * S + u) + n * a * c / D * (a * v^2 * S + r)`:
+
+| | Was (`2a7247653`) | Now |
+|---|---|---|
+| `E` with `t` for `S`, `.Simplify()` | `a * c * (a * t * v ^ 2 + r) / (a ^ 2 * (m + n) + -n * (a * c) ^ 2) + (n * t * w ^ 2 + u) / (a ^ 2 * (m + n) + -n * (a * c) ^ 2) provided not n = 0` | `(-a ^ 2 * c * t * v ^ 2 - a * c * r - n * t * w ^ 2 - u) / (a ^ 2 * c ^ 2 * n - a ^ 2 * m - a ^ 2 * n) provided not n = 0` |
+| `E` with `x` for `S`, `.Simplify()` | `E`, unchanged | `(-a ^ 2 * c * v ^ 2 * x - a * c * r - n * w ^ 2 * x - u) / (a ^ 2 * c ^ 2 * n - a ^ 2 * m - a ^ 2 * n) provided not n = 0` |
+| `RationalCanonicalization.Apply(E)`, either name | no answer | the quotient above |
+
+A refusal now says why, in the new `TransformationResult.Refusal` and after the input in `ToString()`. It names the
+bound reached and the value that passed it, or the part that is not a rational function over `Q`. A greatest common
+divisor that passes its bounds is now a refusal. Before, the quotient came back uncancelled, so two writings of one
+function could give different trees.
+
+| `RationalCanonicalization.Apply(...).ToString()` | Was | Now |
+|---|---|---|
+| `sin(x) / y + 1` | `rational-canonical-form: no answer for sin(x) / y + 1` | the same, then `: not a rational function over Q: sin(x)` |
+| `(1 / x + 1) ^ 40` | `…: no answer for …` | `…: a quotient to the power 40, above the bound of 32` |
+| 17 variables | `…: no answer for …` | `…: 17 variables, above the bound of 16` |
+
### A square system is answered exactly whichever order its equations are in
**Not silent: a decimal answer is now exact, and a refused system has an answer.** The eliminator took the last
diff --git a/Sources/.editorconfig b/Sources/.editorconfig
index fdd52020c..9c6d89c21 100644
--- a/Sources/.editorconfig
+++ b/Sources/.editorconfig
@@ -305,7 +305,7 @@ file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed
[Tests/UnitTests/Core/KnownLimitsAreNotBugsTest.cs]
file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed under MIT.\nDetails: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.\nWebsite: https://am.angouri.org.\n
-[AngouriMath/Functions/Algebra/Polynomials/{IntegerPolynomial,PrimeFieldPolynomial,PrimeFieldFactorization,SquareFreeDecomposition,PolynomialFactorization,PolynomialResultant,RationalPolynomial,PartialFractions,RationalFunction,TrigonometricIdentity}.cs]
+[AngouriMath/Functions/Algebra/Polynomials/{IntegerPolynomial,PrimeFieldPolynomial,PrimeFieldFactorization,SquareFreeDecomposition,PolynomialFactorization,PolynomialResultant,RationalPolynomial,PartialFractions,RationalFunction,TrigonometricIdentity,Monomial}.cs]
file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed under MIT.\nDetails: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.\nWebsite: https://am.angouri.org.\n
[Tests/UnitTests/PatternsTest/ParityTest.cs]
diff --git a/Sources/AngouriMath/Convenience/MathS.Polynomials.cs b/Sources/AngouriMath/Convenience/MathS.Polynomials.cs
index 0812141e1..8cbb98c01 100644
--- a/Sources/AngouriMath/Convenience/MathS.Polynomials.cs
+++ b/Sources/AngouriMath/Convenience/MathS.Polynomials.cs
@@ -201,7 +201,7 @@ public static class Polynomials
/// Whether a constant polynomial is 1, so that it need not be printed.
private static bool SameAsOne(MultivariatePolynomial poly)
- => poly.IsConstant && poly.CoefficientOf(0).CompareTo(ERational.One) == 0;
+ => poly.IsConstant && poly.ConstantCoefficient.CompareTo(ERational.One) == 0;
///
/// The factorisation of a polynomial in more than one variable, as an expression.
diff --git a/Sources/AngouriMath/Core/Transformations/Transformation.Catalogue.cs b/Sources/AngouriMath/Core/Transformations/Transformation.Catalogue.cs
index 3232384d6..4844da5b9 100644
--- a/Sources/AngouriMath/Core/Transformations/Transformation.Catalogue.cs
+++ b/Sources/AngouriMath/Core/Transformations/Transformation.Catalogue.cs
@@ -868,6 +868,17 @@ private sealed class RationalCanonicalizationTransformation : Transformation
protected override Entity? ApplyCore(Entity input)
=> RationalFunction.TryCanonicalize(input, out var canonical) ? canonical : null;
+
+ private protected override Entity? ApplyCore(Entity input, out string? refusal)
+ {
+ if (RationalFunction.TryCanonicalizeExplained(input, out var canonical, out var why))
+ {
+ refusal = null;
+ return canonical;
+ }
+ refusal = why.ToString();
+ return null;
+ }
}
private sealed class PolynomialFactorizationTransformation : Transformation
diff --git a/Sources/AngouriMath/Core/Transformations/Transformation.cs b/Sources/AngouriMath/Core/Transformations/Transformation.cs
index 8d45b238a..f6a49fe10 100644
--- a/Sources/AngouriMath/Core/Transformations/Transformation.cs
+++ b/Sources/AngouriMath/Core/Transformations/Transformation.cs
@@ -89,7 +89,19 @@ public TransformationResult Apply(Entity input)
{
if (input is null)
throw new ArgumentNullException(nameof(input));
- return new TransformationResult(this, input, ApplyCore(input));
+ var output = ApplyCore(input, out var refusal);
+ return new TransformationResult(this, input, output, output is null ? refusal : null);
+ }
+
+ ///
+ /// , with why there is no answer where the transformation
+ /// can say: a bound it reached, or a part of the input outside what it reads.
+ /// https://github.com/asc-community/AngouriMath/issues/2721
+ ///
+ private protected virtual Entity? ApplyCore(Entity input, out string? refusal)
+ {
+ refusal = null;
+ return ApplyCore(input);
}
///
diff --git a/Sources/AngouriMath/Core/Transformations/TransformationResult.cs b/Sources/AngouriMath/Core/Transformations/TransformationResult.cs
index c10dc2fa5..dca17f335 100644
--- a/Sources/AngouriMath/Core/Transformations/TransformationResult.cs
+++ b/Sources/AngouriMath/Core/Transformations/TransformationResult.cs
@@ -17,8 +17,15 @@ namespace AngouriMath.Core.Transformations
///
public readonly struct TransformationResult
{
- internal TransformationResult(Transformation transformation, Entity input, Entity? output)
- => (Transformation, Input, Output) = (transformation, input, output);
+ internal TransformationResult(Transformation transformation, Entity input, Entity? output, string? refusal = null)
+ => (Transformation, Input, Output, Refusal) = (transformation, input, output, refusal);
+
+ ///
+ /// Why there is no answer, where the transformation says: a bound it reached and its value,
+ /// or the part of the input it does not read. where there is an
+ /// answer, or where the transformation gives no reason.
+ ///
+ public string? Refusal { get; }
/// The transformation that was applied.
public Transformation Transformation { get; }
@@ -59,7 +66,9 @@ internal TransformationResult(Transformation transformation, Entity input, Entit
///
public override string ToString()
=> Output is null
- ? $"{Transformation.Name}: no answer for {Input.Stringize()}"
+ ? Refusal is null
+ ? $"{Transformation.Name}: no answer for {Input.Stringize()}"
+ : $"{Transformation.Name}: no answer for {Input.Stringize()}: {Refusal}"
: $"{Transformation.Name}: {Input.Stringize()} -> {Output.Stringize()}";
}
}
diff --git a/Sources/AngouriMath/Functions/Algebra/Groebner/Buchberger.cs b/Sources/AngouriMath/Functions/Algebra/Groebner/Buchberger.cs
index 5032d4408..5a0d0650e 100644
--- a/Sources/AngouriMath/Functions/Algebra/Groebner/Buchberger.cs
+++ b/Sources/AngouriMath/Functions/Algebra/Groebner/Buchberger.cs
@@ -181,14 +181,7 @@ static int ChooseNormalStrategy(
/// Buchberger's first criterion: leading monomials sharing no variable give an
/// S-polynomial that always reduces to zero, so it need not be built.
///
- static bool Coprime(ulong left, ulong right)
- {
- for (var variable = 0; variable < MultivariatePolynomial.MaxVariables; variable++)
- if (MultivariatePolynomial.PowerOfMonomial(left, variable) > 0
- && MultivariatePolynomial.PowerOfMonomial(right, variable) > 0)
- return false;
- return true;
- }
+ static bool Coprime(Monomial left, Monomial right) => Monomial.Coprime(left, right);
///
/// The chain criterion: a third basis element whose leading monomial divides this
@@ -197,7 +190,7 @@ static bool Coprime(ulong left, ulong right)
///
static bool IsRedundantByChain(
List basis, List<(int Left, int Right)> pairs,
- MonomialOrder order, int left, int right, ulong lcm)
+ MonomialOrder order, int left, int right, Monomial lcm)
{
for (var k = 0; k < basis.Count; k++)
{
@@ -214,7 +207,7 @@ static bool IsRedundantByChain(
}
static MultivariatePolynomial? SPolynomial(
- MultivariatePolynomial first, MultivariatePolynomial second, MonomialOrder order, ulong lcm)
+ MultivariatePolynomial first, MultivariatePolynomial second, MonomialOrder order, Monomial lcm)
{
var firstLeading = first.LeadingMonomial(order);
var secondLeading = second.LeadingMonomial(order);
diff --git a/Sources/AngouriMath/Functions/Algebra/Groebner/Fglm.cs b/Sources/AngouriMath/Functions/Algebra/Groebner/Fglm.cs
index 369b98324..200051311 100644
--- a/Sources/AngouriMath/Functions/Algebra/Groebner/Fglm.cs
+++ b/Sources/AngouriMath/Functions/Algebra/Groebner/Fglm.cs
@@ -45,16 +45,16 @@ internal static class Fglm
/// zero-dimensional — so running past the ceiling is how a system with infinitely
/// many solutions, or simply too many, announces itself.
///
- internal static List? StandardMonomials(
+ internal static List? StandardMonomials(
IReadOnlyList basis, int variableCount, MonomialOrder order, int ceiling)
{
- var leading = new List(basis.Count);
+ var leading = new List(basis.Count);
foreach (var element in basis)
leading.Add(element.LeadingMonomial(order));
- var standard = new List();
- var queue = new SortedSet { 0UL };
- var seen = new HashSet { 0UL };
+ var standard = new List();
+ var queue = new SortedSet { Monomial.One };
+ var seen = new HashSet { Monomial.One };
while (queue.Count > 0)
{
@@ -104,7 +104,7 @@ internal static class Fglm
return null;
}
- var position = new Dictionary(standard.Count);
+ var position = new Dictionary(standard.Count);
for (var i = 0; i < standard.Count; i++)
position[standard[i]] = i;
@@ -114,15 +114,15 @@ internal static class Fglm
var rowVectors = new List();
var rowCombinations = new List();
var rowPivots = new List();
- var staircase = new List();
+ var staircase = new List();
var lexicographic = new List();
- var lexicographicLeading = new List();
+ var lexicographicLeading = new List();
- // Lexicographic order is integer order under this packing, so a sorted set of the
+ // Lexicographic order is the order Monomial compares in, so a sorted set of the
// packed monomials walks them smallest first, which is what FGLM wants.
- var queue = new SortedSet { 0UL };
- var seen = new HashSet { 0UL };
+ var queue = new SortedSet { Monomial.One };
+ var seen = new HashSet { Monomial.One };
while (queue.Count > 0)
{
diff --git a/Sources/AngouriMath/Functions/Algebra/Groebner/MultivariatePolynomial.Groebner.cs b/Sources/AngouriMath/Functions/Algebra/Groebner/MultivariatePolynomial.Groebner.cs
index c166e7dc1..f9cbfa8b8 100644
--- a/Sources/AngouriMath/Functions/Algebra/Groebner/MultivariatePolynomial.Groebner.cs
+++ b/Sources/AngouriMath/Functions/Algebra/Groebner/MultivariatePolynomial.Groebner.cs
@@ -32,24 +32,27 @@ internal enum MonomialOrder
internal sealed partial class MultivariatePolynomial
{
- internal ERational CoefficientOf(ulong monomial)
+ internal ERational CoefficientOf(Monomial monomial)
=> terms.TryGetValue(monomial, out var value) ? value : ERational.Zero;
- internal IEnumerable Monomials => terms.Keys;
+ internal IEnumerable Monomials => terms.Keys;
- internal static MultivariatePolynomial Term(int variableCount, ulong monomial, ERational coefficient)
+ /// The coefficient of the monomial with every exponent zero.
+ internal ERational ConstantCoefficient => CoefficientOf(Functions.Monomial.One);
+
+ internal static MultivariatePolynomial Term(int variableCount, Monomial monomial, ERational coefficient)
{
- var built = new Dictionary();
+ var built = new Dictionary();
if (!coefficient.IsZero)
built[monomial] = coefficient.InLowestTerms();
return new(variableCount, built);
}
/// The greatest monomial under ; zero if there is none.
- internal ulong LeadingMonomial(MonomialOrder order)
+ internal Monomial LeadingMonomial(MonomialOrder order)
{
var found = false;
- ulong best = 0;
+ var best = Functions.Monomial.One;
foreach (var monomial in terms.Keys)
if (!found || Greater(order, monomial, best))
{
@@ -61,67 +64,37 @@ internal ulong LeadingMonomial(MonomialOrder order)
internal ERational LeadingCoefficient(MonomialOrder order) => terms[LeadingMonomial(order)];
- internal static bool Greater(MonomialOrder order, ulong left, ulong right)
+ internal static bool Greater(MonomialOrder order, Monomial left, Monomial right)
{
if (order is MonomialOrder.Lexicographic)
return left > right;
- int leftDegree = TotalDegree(left), rightDegree = TotalDegree(right);
+ int leftDegree = left.TotalDegree, rightDegree = right.TotalDegree;
if (leftDegree != rightDegree)
return leftDegree > rightDegree;
- for (var variable = MaxVariables - 1; variable >= 0; variable--)
- {
- int here = PowerOf(left, variable), there = PowerOf(right, variable);
- if (here != there)
- return here < there;
- }
- return false;
+ return left.ReverseLexicographicallyAfter(right);
}
- internal static int PowerOfMonomial(ulong monomial, int variable) => PowerOf(monomial, variable);
+ internal static int PowerOfMonomial(Monomial monomial, int variable) => PowerOf(monomial, variable);
- internal static ulong PackMonomial(int variable, int power) => Pack(variable, power);
+ internal static Monomial PackMonomial(int variable, int power) => Pack(variable, power);
- internal static int TotalDegree(ulong monomial)
- {
- var degree = 0;
- for (var variable = 0; variable < MaxVariables; variable++)
- degree += PowerOf(monomial, variable);
- return degree;
- }
+ internal static int TotalDegree(Monomial monomial) => monomial.TotalDegree;
- internal static bool MonomialDivides(ulong divisor, ulong dividend)
- {
- for (var variable = 0; variable < MaxVariables; variable++)
- if (PowerOf(divisor, variable) > PowerOf(dividend, variable))
- return false;
- return true;
- }
+ internal static bool MonomialDivides(Monomial divisor, Monomial dividend) => divisor.Divides(dividend);
/// Only valid where holds.
- internal static ulong MonomialQuotient(ulong dividend, ulong divisor)
- {
- ulong quotient = 0;
- for (var variable = 0; variable < MaxVariables; variable++)
- quotient |= Pack(variable, PowerOf(dividend, variable) - PowerOf(divisor, variable));
- return quotient;
- }
+ internal static Monomial MonomialQuotient(Monomial dividend, Monomial divisor) => dividend - divisor;
- internal static ulong MonomialLcm(ulong left, ulong right)
- {
- ulong lcm = 0;
- for (var variable = 0; variable < MaxVariables; variable++)
- lcm |= Pack(variable, Math.Max(PowerOf(left, variable), PowerOf(right, variable)));
- return lcm;
- }
+ internal static Monomial MonomialLcm(Monomial left, Monomial right) => Functions.Monomial.Lcm(left, right);
///
/// Reaches the private multiplication by a single term, which already refuses rather
/// than wraps when an exponent would outgrow its byte.
///
- internal MultivariatePolynomial? TimesTerm(ulong monomial, ERational coefficient)
+ internal MultivariatePolynomial? TimesTerm(Monomial monomial, ERational coefficient)
=> MultiplyByTerm(monomial, coefficient);
- internal static bool TryTimesMonomials(ulong left, ulong right, int variableCount, out ulong product)
+ internal static bool TryTimesMonomials(Monomial left, Monomial right, int variableCount, out Monomial product)
=> TryMultiplyMonomials(left, right, variableCount, out product);
internal MultivariatePolynomial MakeMonic(MonomialOrder order)
diff --git a/Sources/AngouriMath/Functions/Algebra/Polynomials/BivariateHenselFactorization.cs b/Sources/AngouriMath/Functions/Algebra/Polynomials/BivariateHenselFactorization.cs
index b804b7d56..ea5a4de00 100644
--- a/Sources/AngouriMath/Functions/Algebra/Polynomials/BivariateHenselFactorization.cs
+++ b/Sources/AngouriMath/Functions/Algebra/Polynomials/BivariateHenselFactorization.cs
@@ -565,7 +565,7 @@ private static RationalPolynomial[] MultiplySeries(
continue;
if (!pair.Value.IsConstant)
return null; // a variable other than the two this works in
- coefficients[pair.Key] = pair.Value.CoefficientOf(0);
+ coefficients[pair.Key] = pair.Value.ConstantCoefficient;
}
return RationalPolynomial.Create(coefficients);
}
diff --git a/Sources/AngouriMath/Functions/Algebra/Polynomials/EvaluationHomomorphism.cs b/Sources/AngouriMath/Functions/Algebra/Polynomials/EvaluationHomomorphism.cs
index ca3a96f54..279baa0ef 100644
--- a/Sources/AngouriMath/Functions/Algebra/Polynomials/EvaluationHomomorphism.cs
+++ b/Sources/AngouriMath/Functions/Algebra/Polynomials/EvaluationHomomorphism.cs
@@ -176,7 +176,7 @@ private static bool NextPoint(int[] point, int attempt, int count)
{
if (depth == others.Count)
return poly.IsZero ? ERational.Zero
- : poly.IsConstant ? poly.CoefficientOf(0) : (ERational?)null;
+ : poly.IsConstant ? poly.ConstantCoefficient : (ERational?)null;
var total = ERational.Zero;
var at = EInteger.FromInt32(point[depth]);
diff --git a/Sources/AngouriMath/Functions/Algebra/Polynomials/KroneckerFactorization.cs b/Sources/AngouriMath/Functions/Algebra/Polynomials/KroneckerFactorization.cs
index 27a741c07..f9853202e 100644
--- a/Sources/AngouriMath/Functions/Algebra/Polynomials/KroneckerFactorization.cs
+++ b/Sources/AngouriMath/Functions/Algebra/Polynomials/KroneckerFactorization.cs
@@ -460,7 +460,7 @@ bool Peel(MultivariatePolynomial rest, int depth, int at)
{
if (!rest.IsConstant)
return false;
- coefficients[at] = coefficients[at].Add(rest.CoefficientOf(0));
+ coefficients[at] = coefficients[at].Add(rest.ConstantCoefficient);
return true;
}
foreach (var pair in rest.CoefficientsIn(order[depth]))
diff --git a/Sources/AngouriMath/Functions/Algebra/Polynomials/Monomial.cs b/Sources/AngouriMath/Functions/Algebra/Polynomials/Monomial.cs
new file mode 100644
index 000000000..03b533b5a
--- /dev/null
+++ b/Sources/AngouriMath/Functions/Algebra/Polynomials/Monomial.cs
@@ -0,0 +1,188 @@
+//
+// Copyright (c) 2019-2026 Angouri.
+// AngouriMath is licensed under MIT.
+// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.
+// Website: https://am.angouri.org.
+//
+
+using System;
+
+namespace AngouriMath.Functions
+{
+ ///
+ /// The exponent vector of a monomial of , packed a byte
+ /// to a variable into two words: the first eight variables in high, the next eight in
+ /// low, the first of each in its most significant byte.
+ ///
+ ///
+ ///
+ /// Comparing two of these word by word is the lexicographic order on exponents, which is
+ /// what needs
+ /// and what the Gröbner solver's lexicographic order is.
+ ///
+ ///
+ /// Two words rather than one so that a rational function in nine variables has a
+ /// canonical form. One word held eight, and a ninth was refused, so the canonical form had
+ /// no answer for an expression with nine names in it and Simplify fell back on rules
+ /// whose reach depends on how the names sort.
+ /// https://github.com/asc-community/AngouriMath/issues/2721
+ /// A polynomial in eight variables or fewer leaves low zero, and then hashes and
+ /// compares as its one word did.
+ ///
+ ///
+ internal readonly struct Monomial : IEquatable, IComparable
+ {
+ /// A byte each in two words.
+ internal const int Capacity = 16;
+
+ private const int PerWord = 8;
+ private const int BitsPerVariable = 8;
+ private const ulong PowerMask = 0xFF;
+
+ private readonly ulong high;
+ private readonly ulong low;
+
+ private Monomial(ulong high, ulong low)
+ {
+ this.high = high;
+ this.low = low;
+ }
+
+ /// Every exponent zero: the monomial of a constant.
+ internal static Monomial One => default;
+
+ internal bool IsOne => (high | low) == 0;
+
+ private static int ShiftOf(int variable) => (PerWord - 1 - variable % PerWord) * BitsPerVariable;
+
+ /// to , which has to fit in a byte.
+ internal static Monomial Of(int variable, int power)
+ {
+ var packed = (ulong)power << ShiftOf(variable);
+ return variable < PerWord ? new(packed, 0) : new(0, packed);
+ }
+
+ internal int PowerOf(int variable)
+ => (int)(((variable < PerWord ? high : low) >> ShiftOf(variable)) & PowerMask);
+
+ /// The same monomial with to the power zero.
+ internal Monomial Without(int variable)
+ {
+ var mask = ~(PowerMask << ShiftOf(variable));
+ return variable < PerWord ? new(high & mask, low) : new(high, low & mask);
+ }
+
+ /// The union of two monomials sharing no variable.
+ public static Monomial operator |(Monomial left, Monomial right)
+ => new(left.high | right.high, left.low | right.low);
+
+ ///
+ /// The product, exponent by exponent. Exact where no exponent of the sum passes a
+ /// byte, which checks and this does not.
+ ///
+ public static Monomial operator +(Monomial left, Monomial right)
+ => new(left.high + right.high, left.low + right.low);
+
+ ///
+ /// The quotient, exponent by exponent. Exact where divides
+ /// , which checks and this does not.
+ ///
+ public static Monomial operator -(Monomial left, Monomial right)
+ => new(left.high - right.high, left.low - right.low);
+
+ // Every exponent is at most MultivariatePolynomial.MaxDegree, 127, so the top bit of
+ // each byte is clear. That bit is what lets a whole word of exponents be added,
+ // compared or tested at once: a byte cannot carry into its neighbour.
+ private const ulong TopBits = 0x8080808080808080UL;
+ private const ulong BelowTopBits = 0x7F7F7F7F7F7F7F7FUL;
+ private const ulong EvenBytes = 0x00FF00FF00FF00FFUL;
+
+ ///
+ /// The product, or where an exponent of it would pass
+ /// : where the top bit of its byte is set.
+ ///
+ internal static bool TryMultiply(Monomial left, Monomial right, out Monomial product)
+ {
+ product = left + right;
+ return ((product.high | product.low) & TopBits) == 0;
+ }
+
+ /// Whether every exponent of this is at most the same exponent of .
+ internal bool Divides(Monomial multiple)
+ => (((multiple.high | TopBits) - high) & TopBits) == TopBits
+ && (((multiple.low | TopBits) - low) & TopBits) == TopBits;
+
+ /// Whether no variable occurs in both.
+ internal static bool Coprime(Monomial left, Monomial right)
+ => (Occurring(left.high) & Occurring(right.high)) == 0
+ && (Occurring(left.low) & Occurring(right.low)) == 0;
+
+ /// The top bit of each byte that is not zero.
+ private static ulong Occurring(ulong word) => (word + BelowTopBits) & TopBits;
+
+ /// The least common multiple: the larger exponent of each variable.
+ internal static Monomial Lcm(Monomial left, Monomial right)
+ => new(Larger(left.high, right.high), Larger(left.low, right.low));
+
+ private static ulong Larger(ulong left, ulong right)
+ {
+ // The top bit of each byte where the left one is at least the right one, then
+ // that bit spread over its byte.
+ var leftWins = (((left | TopBits) - right) & TopBits) >> 7;
+ var mask = leftWins * 0xFF;
+ return (left & mask) | (right & ~mask);
+ }
+
+ /// The sum of the exponents.
+ internal int TotalDegree => SumOfBytes(high) + SumOfBytes(low);
+
+ private static int SumOfBytes(ulong word)
+ {
+ // Pairs of bytes into four sixteen-bit lanes, each at most 254, whose sum, at
+ // most 1016, the multiplication gathers into the top lane.
+ var pairs = (word & EvenBytes) + ((word >> 8) & EvenBytes);
+ return (int)((pairs * 0x0001000100010001UL) >> 48);
+ }
+
+ ///
+ /// Of two monomials of the same total degree, whether this one comes later in the
+ /// degree reverse lexicographic order: in the last variable where they differ, its
+ /// exponent is the smaller.
+ ///
+ internal bool ReverseLexicographicallyAfter(Monomial other)
+ => low != other.low ? LastByteSmaller(low, other.low) : LastByteSmaller(high, other.high);
+
+ private static bool LastByteSmaller(ulong here, ulong there)
+ {
+ for (var shift = 0; shift < 64; shift += BitsPerVariable)
+ {
+ ulong mine = (here >> shift) & PowerMask, theirs = (there >> shift) & PowerMask;
+ if (mine != theirs)
+ return mine < theirs;
+ }
+ return false;
+ }
+
+ public int CompareTo(Monomial other)
+ {
+ var byHigh = high.CompareTo(other.high);
+ return byHigh != 0 ? byHigh : low.CompareTo(other.low);
+ }
+
+ public static bool operator >(Monomial left, Monomial right) => left.CompareTo(right) > 0;
+
+ public static bool operator <(Monomial left, Monomial right) => left.CompareTo(right) < 0;
+
+ public bool Equals(Monomial other) => high == other.high && low == other.low;
+
+ public override bool Equals(object? obj) => obj is Monomial other && Equals(other);
+
+ public static bool operator ==(Monomial left, Monomial right) => left.Equals(right);
+
+ public static bool operator !=(Monomial left, Monomial right) => !left.Equals(right);
+
+ public override int GetHashCode() => (high ^ (low * 0x9E3779B97F4A7C15UL)).GetHashCode();
+
+ public override string ToString() => $"{high:X16}{low:X16}";
+ }
+}
diff --git a/Sources/AngouriMath/Functions/Algebra/Polynomials/MultivariateHenselFactorization.cs b/Sources/AngouriMath/Functions/Algebra/Polynomials/MultivariateHenselFactorization.cs
index d05dab84b..55be1fd25 100644
--- a/Sources/AngouriMath/Functions/Algebra/Polynomials/MultivariateHenselFactorization.cs
+++ b/Sources/AngouriMath/Functions/Algebra/Polynomials/MultivariateHenselFactorization.cs
@@ -300,7 +300,7 @@ private static int[] PointFor(int attempt, int count)
|| slice.DivideExact(product, MultivariatePolynomial.MaxIntermediateTerms) is not { IsConstant: true } constant
|| constant.IsZero)
return null;
- factors[0] = factors[0].ScaleBy(constant.CoefficientOf(0));
+ factors[0] = factors[0].ScaleBy(constant.ConstantCoefficient);
if (UnivariateDiophantine.Create(factors, main, first) is not { } solver)
return null;
@@ -593,7 +593,7 @@ private static MultivariatePolynomial AtZero(MultivariatePolynomial poly, int va
{
if (depth == others.Count)
return poly.IsZero ? ERational.Zero
- : poly.IsConstant ? poly.CoefficientOf(0) : (ERational?)null;
+ : poly.IsConstant ? poly.ConstantCoefficient : (ERational?)null;
var total = ERational.Zero;
var at = EInteger.FromInt32(point[depth]);
foreach (var pair in poly.CoefficientsIn(others[depth]))
@@ -617,7 +617,7 @@ private static MultivariatePolynomial AtZero(MultivariatePolynomial poly, int va
continue;
if (!pair.Value.IsConstant)
return null;
- coefficients[pair.Key] = pair.Value.CoefficientOf(0);
+ coefficients[pair.Key] = pair.Value.ConstantCoefficient;
}
return RationalPolynomial.Create(coefficients);
}
diff --git a/Sources/AngouriMath/Functions/Algebra/Polynomials/MultivariatePolynomial.cs b/Sources/AngouriMath/Functions/Algebra/Polynomials/MultivariatePolynomial.cs
index 6f28ae0d1..384d8842d 100644
--- a/Sources/AngouriMath/Functions/Algebra/Polynomials/MultivariatePolynomial.cs
+++ b/Sources/AngouriMath/Functions/Algebra/Polynomials/MultivariatePolynomial.cs
@@ -22,11 +22,11 @@ namespace AngouriMath.Functions
/// whether sqrt(2) - a is zero is as hard as the problem that sent us here, and
/// a divisor wrongly believed nonzero produces a wrong cancellation rather than a
/// missing one. Anything outside Q is refused at the door by
- /// .
+ /// .
///
///
- /// An exponent vector is packed into one , a byte to a variable,
- /// the first variable in the most significant byte. Comparing packed monomials is then
+ /// An exponent vector is a , a byte to a variable, the
+ /// first variable in the most significant byte. Comparing packed monomials is then
/// exactly the lexicographic order on exponents that needs,
/// and looking a monomial up costs one hash.
///
@@ -47,7 +47,19 @@ namespace AngouriMath.Functions
///
internal sealed partial class MultivariatePolynomial
{
- /// One byte of the packed monomial each, so eight of them fit.
+ ///
+ /// The most variables the solvers, the integrator, the evaluator and the quantifier
+ /// rules ask this about, and what
+ /// reads unless told otherwise.
+ ///
+ ///
+ /// It was the most a packed monomial held, one byte each in one word. A
+ /// holds now, and only
+ /// the rational canonical form reads that many: what it does with a polynomial is bounded
+ /// by the term count, while the searches the other callers run grow with the number of
+ /// variables, and none of them has been measured past eight.
+ /// https://github.com/asc-community/AngouriMath/issues/2721
+ ///
internal const int MaxVariables = 8;
///
@@ -84,28 +96,25 @@ internal sealed partial class MultivariatePolynomial
///
internal const int MaxIntermediateTerms = 4096;
- private const int BitsPerVariable = 8;
- private const ulong PowerMask = 0xFF;
-
/// Monomial to its coefficient. A zero coefficient is never stored.
- private readonly Dictionary terms;
+ private readonly Dictionary terms;
internal int VariableCount { get; }
- private MultivariatePolynomial(int variableCount, Dictionary terms)
+ private MultivariatePolynomial(int variableCount, Dictionary terms)
{
VariableCount = variableCount;
this.terms = terms;
}
internal static MultivariatePolynomial Zero(int variableCount)
- => new(variableCount, new Dictionary());
+ => new(variableCount, new Dictionary());
internal static MultivariatePolynomial Constant(int variableCount, ERational value)
{
- var terms = new Dictionary();
+ var terms = new Dictionary();
if (!value.IsZero)
- terms[0] = value.InLowestTerms();
+ terms[Functions.Monomial.One] = value.InLowestTerms();
return new(variableCount, terms);
}
@@ -113,22 +122,19 @@ internal static MultivariatePolynomial One(int variableCount)
=> Constant(variableCount, ERational.One);
internal static MultivariatePolynomial Monomial(int variableCount, int variable)
- => new(variableCount, new Dictionary { [Pack(variable, 1)] = ERational.One });
+ => new(variableCount, new Dictionary { [Pack(variable, 1)] = ERational.One });
internal bool IsZero => terms.Count == 0;
- internal bool IsConstant => terms.Count == 0 || (terms.Count == 1 && terms.ContainsKey(0));
+ internal bool IsConstant => terms.Count == 0 || (terms.Count == 1 && terms.ContainsKey(Functions.Monomial.One));
internal int TermCount => terms.Count;
- private static int ShiftOf(int variable) => (MaxVariables - 1 - variable) * BitsPerVariable;
+ internal static int PowerOf(Monomial monomial, int variable) => monomial.PowerOf(variable);
- internal static int PowerOf(ulong monomial, int variable)
- => (int)((monomial >> ShiftOf(variable)) & PowerMask);
+ private static Monomial Pack(int variable, int power) => Functions.Monomial.Of(variable, power);
- private static ulong Pack(int variable, int power) => (ulong)power << ShiftOf(variable);
-
- private static ulong Without(ulong monomial, int variable) => monomial & ~Pack(variable, (int)PowerMask);
+ private static Monomial Without(Monomial monomial, int variable) => monomial.Without(variable);
///
/// The highest power of occurring. Zero both for a
@@ -160,9 +166,9 @@ internal int Degree
}
/// The greatest monomial in lexicographic order; zero if there is none.
- private ulong LeadingMonomial()
+ private Monomial LeadingMonomial()
{
- ulong leading = 0;
+ var leading = Functions.Monomial.One;
foreach (var monomial in terms.Keys)
if (monomial > leading)
leading = monomial;
@@ -175,13 +181,13 @@ private ulong LeadingMonomial()
private MultivariatePolynomial Combine(MultivariatePolynomial other, bool subtract)
{
- var result = new Dictionary(terms);
+ var result = new Dictionary(terms);
foreach (var term in other.terms)
Accumulate(result, term.Key, subtract ? term.Value.Negate() : term.Value);
return new(VariableCount, result);
}
- private static void Accumulate(Dictionary into, ulong monomial, ERational value)
+ private static void Accumulate(Dictionary into, Monomial monomial, ERational value)
{
if (!into.TryGetValue(monomial, out var existing))
{
@@ -200,7 +206,7 @@ private static void Accumulate(Dictionary into, ulong monomial
{
if (IsZero || other.IsZero)
return Zero(VariableCount);
- var result = new Dictionary();
+ var result = new Dictionary();
foreach (var left in terms)
foreach (var right in other.terms)
{
@@ -238,13 +244,13 @@ private static void Accumulate(Dictionary into, ulong monomial
}
/// The packed monomial of to the first power.
- internal static ulong MonomialOf(int variable) => Pack(variable, 1);
+ internal static Monomial MonomialOf(int variable) => Pack(variable, 1);
internal MultivariatePolynomial ScaleBy(ERational factor)
{
if (factor.IsZero)
return Zero(VariableCount);
- var result = new Dictionary(terms.Count);
+ var result = new Dictionary(terms.Count);
foreach (var term in terms)
result[term.Key] = term.Value.Multiply(factor).InLowestTerms();
return new(VariableCount, result);
@@ -255,7 +261,7 @@ internal MultivariatePolynomial ScaleBy(ERational factor)
{
if (power == 0)
return this;
- var result = new Dictionary(terms.Count);
+ var result = new Dictionary(terms.Count);
foreach (var term in terms)
{
var raised = PowerOf(term.Key, variable) + power;
@@ -267,7 +273,7 @@ internal MultivariatePolynomial ScaleBy(ERational factor)
}
/// The terms, each as its packed monomial and its coefficient.
- internal IEnumerable> Terms => terms;
+ internal IEnumerable> Terms => terms;
/// Whether every coefficient is a whole number.
internal bool HasIntegerCoefficients
@@ -311,12 +317,12 @@ internal bool HasIntegerCoefficients
///
internal Dictionary CoefficientsIn(int variable)
{
- var buckets = new Dictionary>();
+ var buckets = new Dictionary>();
foreach (var term in terms)
{
var power = PowerOf(term.Key, variable);
if (!buckets.TryGetValue(power, out var bucket))
- buckets[power] = bucket = new Dictionary();
+ buckets[power] = bucket = new Dictionary();
bucket[Without(term.Key, variable)] = term.Value;
}
var result = new Dictionary(buckets.Count);
@@ -332,7 +338,7 @@ internal Dictionary CoefficientsIn(int variable)
///
internal MultivariatePolynomial DerivativeIn(int variable)
{
- var result = new Dictionary();
+ var result = new Dictionary();
foreach (var term in terms)
{
var power = PowerOf(term.Key, variable);
@@ -403,7 +409,7 @@ internal MultivariatePolynomial DerivativeIn(int variable)
///
internal MultivariatePolynomial Truncated(IReadOnlyList bounds)
{
- var result = new Dictionary(terms.Count);
+ var result = new Dictionary(terms.Count);
foreach (var term in terms)
{
var keep = true;
@@ -418,7 +424,7 @@ internal MultivariatePolynomial Truncated(IReadOnlyList bounds)
internal MultivariatePolynomial LeadingCoefficientIn(int variable)
{
var degree = DegreeIn(variable);
- var result = new Dictionary();
+ var result = new Dictionary();
foreach (var term in terms)
if (PowerOf(term.Key, variable) == degree)
result[Without(term.Key, variable)] = term.Value;
@@ -462,11 +468,11 @@ internal MultivariatePolynomial LeadingCoefficientIn(int variable)
if (IsZero)
return Zero(VariableCount);
if (divisor.IsConstant)
- return ScaleBy(ERational.One.Divide(divisor.terms[0]));
+ return ScaleBy(ERational.One.Divide(divisor.terms[Functions.Monomial.One]));
var divisorLead = divisor.LeadingMonomial();
var divisorValue = divisor.terms[divisorLead];
- var quotient = new Dictionary();
+ var quotient = new Dictionary();
var rest = this;
for (var step = 0; step <= maxTerms; step++)
{
@@ -495,9 +501,9 @@ internal MultivariatePolynomial LeadingCoefficientIn(int variable)
return null;
}
- private MultivariatePolynomial? MultiplyByTerm(ulong monomial, ERational value)
+ private MultivariatePolynomial? MultiplyByTerm(Monomial monomial, ERational value)
{
- var result = new Dictionary(terms.Count);
+ var result = new Dictionary(terms.Count);
foreach (var term in terms)
{
if (!TryMultiplyMonomials(term.Key, monomial, VariableCount, out var product))
@@ -507,30 +513,13 @@ internal MultivariatePolynomial LeadingCoefficientIn(int variable)
return new(VariableCount, result);
}
- private static bool TryMultiplyMonomials(ulong left, ulong right, int variableCount, out ulong product)
- {
- product = 0;
- for (var i = 0; i < variableCount; i++)
- {
- var power = PowerOf(left, i) + PowerOf(right, i);
- if (power > MaxDegree)
- return false;
- product |= Pack(i, power);
- }
- return true;
- }
+ private static bool TryMultiplyMonomials(Monomial left, Monomial right, int variableCount, out Monomial product)
+ => Functions.Monomial.TryMultiply(left, right, out product);
- private static bool TryDivideMonomials(ulong dividend, ulong divisor, int variableCount, out ulong quotient)
+ private static bool TryDivideMonomials(Monomial dividend, Monomial divisor, int variableCount, out Monomial quotient)
{
- quotient = 0;
- for (var i = 0; i < variableCount; i++)
- {
- var power = PowerOf(dividend, i) - PowerOf(divisor, i);
- if (power < 0)
- return false;
- quotient |= Pack(i, power);
- }
- return true;
+ quotient = dividend - divisor;
+ return divisor.Divides(dividend);
}
///
@@ -592,12 +581,23 @@ internal bool SameAs(MultivariatePolynomial other)
/// before it is built rather than after.
///
internal static MultivariatePolynomial? TryParse(Entity expr, IReadOnlyDictionary variables)
- // A ninth variable has no byte of the packed monomial to live in, and the shift
- // that would address it is negative, which the language turns into a shift by
- // 56 -- the first variable's byte. So it would not fail, it would silently be
- // the first variable, and x_1 - x_9 would read as the zero polynomial. Refused
- // here rather than guarded at each caller, since the packing is this type's.
- => variables.Count > MaxVariables ? null : expr switch
+ => TryParse(expr, variables, MaxVariables);
+
+ ///
+ /// , in up to
+ /// variables, which may be as many as
+ /// .
+ ///
+ internal static MultivariatePolynomial? TryParse(Entity expr, IReadOnlyDictionary variables, int mostVariables)
+ // A variable past the capacity has no byte of the packed monomial to live in, and
+ // the shift that would address it wraps round to another variable's byte. So it
+ // would not fail, it would silently be that variable, and x_1 - x_17 would read as
+ // the zero polynomial. Refused here rather than guarded at each caller, since the
+ // packing is this type's.
+ => variables.Count > System.Math.Min(mostVariables, Functions.Monomial.Capacity) ? null : Parse(expr, variables);
+
+ private static MultivariatePolynomial? Parse(Entity expr, IReadOnlyDictionary variables)
+ => expr switch
{
// Integer is a Rational, so this arm takes both.
Rational rational => Constant(variables.Count, rational.ERational),
@@ -605,17 +605,17 @@ internal bool SameAs(MultivariatePolynomial other)
? Monomial(variables.Count, index)
: null,
Sumf(var augend, var addend) =>
- TryParse(augend, variables) is { } left && TryParse(addend, variables) is { } right
+ Parse(augend, variables) is { } left && Parse(addend, variables) is { } right
? left.Add(right) : null,
Minusf(var subtrahend, var minuend) =>
- TryParse(subtrahend, variables) is { } left && TryParse(minuend, variables) is { } right
+ Parse(subtrahend, variables) is { } left && Parse(minuend, variables) is { } right
? left.Subtract(right) : null,
Mulf(var multiplier, var multiplicand) =>
- TryParse(multiplier, variables) is { } left && TryParse(multiplicand, variables) is { } right
+ Parse(multiplier, variables) is { } left && Parse(multiplicand, variables) is { } right
? left.Multiply(right) : null,
Divf(var dividend, var divisor) =>
- TryParse(divisor, variables) is { IsConstant: true, IsZero: false } bottom
- && TryParse(dividend, variables) is { } top
+ Parse(divisor, variables) is { IsConstant: true, IsZero: false } bottom
+ && Parse(dividend, variables) is { } top
? top.ScaleBy(ERational.One.Divide(bottom.ConstantValue)) : null,
Powf(var @base, Integer exponent) => ParsePower(@base, exponent, variables),
_ => null
@@ -629,7 +629,7 @@ internal bool SameAs(MultivariatePolynomial other)
var power = exponent.EInteger.ToInt32Checked();
if (power > MaxDegree || power < -MaxDegree)
return null;
- if (TryParse(@base, variables) is not { } parsed)
+ if (Parse(@base, variables) is not { } parsed)
return null;
if (power >= 0)
return parsed.Power(power);
@@ -644,7 +644,7 @@ internal bool SameAs(MultivariatePolynomial other)
return Constant(variables.Count, result);
}
- private ERational ConstantValue => terms.Count == 0 ? ERational.Zero : terms[0];
+ private ERational ConstantValue => terms.Count == 0 ? ERational.Zero : terms[Functions.Monomial.One];
internal Entity ToEntity(IReadOnlyList variables)
{
diff --git a/Sources/AngouriMath/Functions/Algebra/Polynomials/PartialFractions.cs b/Sources/AngouriMath/Functions/Algebra/Polynomials/PartialFractions.cs
index c3292e9f4..5ee33c8c2 100644
--- a/Sources/AngouriMath/Functions/Algebra/Polynomials/PartialFractions.cs
+++ b/Sources/AngouriMath/Functions/Algebra/Polynomials/PartialFractions.cs
@@ -2416,6 +2416,17 @@ internal static bool TrySolveOverPolynomials(Entity[][] matrix, Entity[] rhs, [N
private sealed class ModularElimination
{
private const long Prime = LiftingPrime;
+
+ ///
+ /// A monomial here is one word, a byte to a variable and the first variable in the
+ /// top byte, so that the heap and the table compare and hash it in one instruction.
+ /// That holds the variables
+ /// reads, and is the order
+ /// compares in.
+ ///
+ private static int PowerOf(ulong monomial, int variable) => (int)((monomial >> ((7 - variable) * 8)) & 0xFF);
+
+ private static ulong MonomialOf(int variable) => 1UL << ((7 - variable) * 8);
private const int MaxTerms = MultivariatePolynomial.MaxIntermediateTerms;
/// Past this many monomials held, a product or a remainder is not followed.
@@ -2458,7 +2469,7 @@ internal void Hold(int count)
for (var i = 0; i < count; i++)
for (var variable = 0; variable < Degrees.Length; variable++)
{
- var power = MultivariatePolynomial.PowerOf(Monomials[i], variable);
+ var power = PowerOf(Monomials[i], variable);
if (power > Degrees[variable])
Degrees[variable] = power;
}
@@ -2551,7 +2562,7 @@ internal static bool Declines(Entity[][] matrix, Entity[] rhs, IReadOnlyDictiona
}
///
- /// The image of what reads
+ /// The image of what reads
/// as, read the same way: where
/// that refuses it -- a node that is not a polynomial, a product or a power past
/// terms or its degree -- and
@@ -2575,7 +2586,7 @@ private Outcome Read(Entity expr, IReadOnlyDictionary indices, ou
case Variable variable:
if (!indices.TryGetValue(variable, out var index))
return Outcome.Declines;
- image = new Image(new[] { MultivariatePolynomial.MonomialOf(index) }, new long[] { 1 }, 1, variableCount);
+ image = new Image(new[] { MonomialOf(index) }, new long[] { 1 }, 1, variableCount);
return Outcome.Continues;
case Sumf or Minusf:
return Sum(expr, indices, out image);
@@ -2754,18 +2765,18 @@ private bool TryReadAMonomial(Entity term, IReadOnlyDictionary in
coefficient = residue;
return true;
case Variable variable when indices.TryGetValue(variable, out var index):
- monomial = MultivariatePolynomial.MonomialOf(index);
+ monomial = MonomialOf(index);
return true;
case Powf(Variable variable, Integer power) when indices.TryGetValue(variable, out var index)
&& power.EInteger.Sign >= 0 && power.EInteger.CompareTo(MultivariatePolynomial.MaxDegree) <= 0:
- monomial = MultivariatePolynomial.MonomialOf(index) * (ulong)power.EInteger.ToInt32Checked();
+ monomial = MonomialOf(index) * (ulong)power.EInteger.ToInt32Checked();
return true;
case Mulf(var multiplier, var multiplicand):
if (!TryReadAMonomial(multiplier, indices, out var left, out var leftCoefficient)
|| !TryReadAMonomial(multiplicand, indices, out var right, out var rightCoefficient))
return false;
for (var variable = 0; variable < variableCount; variable++)
- if (MultivariatePolynomial.PowerOf(left, variable) + MultivariatePolynomial.PowerOf(right, variable) > MultivariatePolynomial.MaxDegree)
+ if (PowerOf(left, variable) + PowerOf(right, variable) > MultivariatePolynomial.MaxDegree)
return false;
monomial = left + right;
coefficient = Multiply(leftCoefficient, rightCoefficient);
@@ -2894,7 +2905,7 @@ private Outcome Divided(Image divisor, Image? recycled, out Image? divided)
if (!TryDivideMonomials(monomial, leadMonomial, out var quotient))
return Outcome.Unknown;
for (var variable = 0; variable < variableCount; variable++)
- if (MultivariatePolynomial.PowerOf(quotient, variable) + divisor.Degrees[variable] > MultivariatePolynomial.MaxDegree)
+ if (PowerOf(quotient, variable) + divisor.Degrees[variable] > MultivariatePolynomial.MaxDegree)
return Outcome.Unknown;
var scale = Multiply(value, leadInverse);
if (count == MaxTerms)
@@ -2935,7 +2946,7 @@ private bool TryDivideMonomials(ulong dividend, ulong divisor, out ulong quotien
{
quotient = 0;
for (var variable = 0; variable < variableCount; variable++)
- if (MultivariatePolynomial.PowerOf(dividend, variable) < MultivariatePolynomial.PowerOf(divisor, variable))
+ if (PowerOf(dividend, variable) < PowerOf(divisor, variable))
return false;
// No byte borrows from the next, since none is smaller than the divisor's.
quotient = dividend - divisor;
diff --git a/Sources/AngouriMath/Functions/Algebra/Polynomials/PolynomialGcd.cs b/Sources/AngouriMath/Functions/Algebra/Polynomials/PolynomialGcd.cs
index ee69ac404..4b2902291 100644
--- a/Sources/AngouriMath/Functions/Algebra/Polynomials/PolynomialGcd.cs
+++ b/Sources/AngouriMath/Functions/Algebra/Polynomials/PolynomialGcd.cs
@@ -60,7 +60,7 @@ internal static class PolynomialGcd
/// Enough for any sequence a polynomial within the degree bound can produce; a
/// cheap ceiling so that a mistake shows up as a refusal rather than a hang.
///
- private const int MaxSteps = 256;
+ internal const int MaxSteps = 256;
///
/// Puts numerator / denominator into lowest terms, or answers
@@ -140,7 +140,7 @@ internal static bool TryCancel(Entity numerator, Entity denominator,
internal static MultivariatePolynomial? Gcd(
MultivariatePolynomial left, MultivariatePolynomial right, IReadOnlyList variables, int depth)
{
- if (depth > MultivariatePolynomial.MaxVariables)
+ if (depth > Monomial.Capacity)
return null;
if (left.IsZero)
return right.Normalized();
diff --git a/Sources/AngouriMath/Functions/Algebra/Polynomials/RationalFunction.cs b/Sources/AngouriMath/Functions/Algebra/Polynomials/RationalFunction.cs
index 41afc14c1..2924f853b 100644
--- a/Sources/AngouriMath/Functions/Algebra/Polynomials/RationalFunction.cs
+++ b/Sources/AngouriMath/Functions/Algebra/Polynomials/RationalFunction.cs
@@ -56,7 +56,7 @@ internal static class RationalFunction
/// A quotient larger than this is left alone. On node count, and a refusal rather
/// than an approximation.
///
- private const int MaxComplexity = 256;
+ internal const int MaxComplexity = 256;
///
/// Raising a quotient to a power is where a gathered quotient explodes, so a power of
@@ -64,7 +64,7 @@ internal static class RationalFunction
/// power has 's own bound on the number of
/// terms.
///
- private const int MaxExponent = 32;
+ internal const int MaxExponent = 32;
///
/// as a canonical quotient of polynomials over Q, or
@@ -79,27 +79,54 @@ internal static class RationalFunction
/// either way, and still one tree per function; the monic form is the specification's,
/// and this is the one written for a reader, as Simplify offers it.
internal static bool TryCanonicalize(Entity expr, [NotNullWhen(true)] out Entity? canonical, bool wholeCoefficients = false)
+ => TryCanonicalizeExplained(expr, out canonical, out _, wholeCoefficients);
+
+ ///
+ /// , saying why there is no answer: a bound reached, which
+ /// one and its value, or a part that is not a rational function over Q.
+ /// https://github.com/asc-community/AngouriMath/issues/2721
+ ///
+ ///
+ /// The refusal is a value and not a string, so that Simplify, which asks this on
+ /// every rational function it meets and only wants the answer, formats nothing.
+ ///
+ internal static bool TryCanonicalizeExplained(Entity expr, [NotNullWhen(true)] out Entity? canonical,
+ out RationalRefusal refusal, bool wholeCoefficients = false)
{
canonical = null;
+ refusal = default;
if (expr.Complexity > MaxComplexity)
+ {
+ refusal = new(RationalRefusalKind.Complexity, expr.Complexity);
return false;
+ }
var variables = expr.Vars
.OrderBy(variable => variable.Name, StringComparer.Ordinal)
.ToArray();
- if (variables.Length > MultivariatePolynomial.MaxVariables)
+ // As many variables as a monomial holds, and not the fewer the solvers ask about: a
+ // quotient in nine has a canonical form as much as one in eight, and refusing it left
+ // Simplify to rules whose reach depends on how the names sort.
+ // https://github.com/asc-community/AngouriMath/issues/2721
+ if (variables.Length > Monomial.Capacity)
+ {
+ refusal = new(RationalRefusalKind.Variables, variables.Length);
return false;
+ }
var indices = new Dictionary(variables.Length);
for (var i = 0; i < variables.Length; i++)
indices[variables[i]] = i;
var variableCount = variables.Length;
- if (!TryGather(expr, indices, variableCount, out var numerator, out var denominator, out var excluded))
+ if (!TryGather(expr, indices, variableCount, out var numerator, out var denominator, out var excluded, out refusal))
return false;
// A vanishing denominator is not a rational function. A vanishing numerator is zero
// wherever the expression has a value: everywhere its denominator does not vanish.
if (denominator.IsZero)
+ {
+ refusal = new(RationalRefusalKind.ZeroDenominator);
return false;
+ }
var order = new int[variableCount];
for (var i = 0; i < order.Length; i++)
order[i] = i;
@@ -107,27 +134,38 @@ internal static bool TryCanonicalize(Entity expr, [NotNullWhen(true)] out Entity
{
if (excluded.Multiply(denominator) is not { } wholeDenominator
|| Conditioned(Integer.Create(0), wholeDenominator, MultivariatePolynomial.One(variableCount), order, variables) is not { } zero)
+ {
+ refusal = new(RationalRefusalKind.Divisor);
return false;
+ }
canonical = zero;
return true;
}
- if (variableCount > 0
- && PolynomialGcd.Gcd(numerator, denominator, order, 0) is { } divisor
- && !divisor.IsConstant)
+ // A greatest common divisor the machinery declined to compute is a refusal, not a
+ // divisor of 1: the quotient would come out uncancelled, and two writings of one
+ // function would then not meet, which is the one thing a canonical form promises.
+ MultivariatePolynomial? divisor = null;
+ if (variableCount > 0 && (divisor = PolynomialGcd.Gcd(numerator, denominator, order, 0)) is null)
+ {
+ refusal = new(RationalRefusalKind.Divisor);
+ return false;
+ }
+ if (divisor is { IsConstant: false })
{
- if (numerator.DivideExact(divisor) is not { } reducedTop
- || denominator.DivideExact(divisor) is not { } reducedBottom)
- return false;
// Multiplied back independently of the division that produced them, as
// PolynomialGcd does for the same reason: an incomplete cancellation is a
// tolerable answer and a wrong one is not.
- if (reducedTop.Multiply(divisor) is not { } checkedTop || !checkedTop.SameAs(numerator)
+ if (numerator.DivideExact(divisor) is not { } reducedTop
+ || denominator.DivideExact(divisor) is not { } reducedBottom
+ || reducedTop.Multiply(divisor) is not { } checkedTop || !checkedTop.SameAs(numerator)
|| reducedBottom.Multiply(divisor) is not { } checkedBottom
- || !checkedBottom.SameAs(denominator))
- return false;
- if (excluded.Multiply(divisor) is not { } withTheCancelled)
+ || !checkedBottom.SameAs(denominator)
+ || excluded.Multiply(divisor) is not { } withTheCancelled)
+ {
+ refusal = new(RationalRefusalKind.Divisor);
return false;
+ }
numerator = reducedTop;
denominator = reducedBottom;
excluded = withTheCancelled;
@@ -139,7 +177,10 @@ internal static bool TryCanonicalize(Entity expr, [NotNullWhen(true)] out Entity
// unit, and nothing obliges the machinery to take the 2 out.
var leading = denominator.LeadingCoefficient(MonomialOrder.Lexicographic);
if (leading.IsZero)
+ {
+ refusal = new(RationalRefusalKind.ZeroDenominator);
return false;
+ }
if (leading.CompareTo(ERational.One) != 0)
{
var inverse = ERational.One.Divide(leading).InLowestTerms();
@@ -157,6 +198,8 @@ internal static bool TryCanonicalize(Entity expr, [NotNullWhen(true)] out Entity
? numerator.ToEntity(variables)
: numerator.ToEntity(variables) / denominator.ToEntity(variables);
canonical = Conditioned(quotient, excluded, denominator, order, variables);
+ if (canonical is null)
+ refusal = new(RationalRefusalKind.Divisor);
return canonical is not null;
}
@@ -214,29 +257,167 @@ private static bool TryGather(
Entity expr, IReadOnlyDictionary indices, int variableCount,
[NotNullWhen(true)] out MultivariatePolynomial? numerator,
[NotNullWhen(true)] out MultivariatePolynomial? denominator,
- [NotNullWhen(true)] out MultivariatePolynomial? excluded)
+ [NotNullWhen(true)] out MultivariatePolynomial? excluded,
+ out RationalRefusal refusal)
{
numerator = denominator = excluded = null;
+ refusal = default;
+ if (NotRational(expr, indices) is { } offending)
+ {
+ refusal = new(RationalRefusalKind.NotRational, offending: offending);
+ return false;
+ }
foreach (var node in expr.Nodes)
if (node is Powf(var @base, Integer power)
&& power.EInteger.Abs().CompareTo(EInteger.FromInt32(MaxExponent)) > 0
- && MultivariatePolynomial.TryParse(@base, indices) is null)
+ && MultivariatePolynomial.TryParse(@base, indices, Monomial.Capacity) is null)
+ {
+ refusal = new(RationalRefusalKind.Exponent, power.EInteger.CanFitInInt32() ? power.EInteger.ToInt32Checked() : int.MaxValue);
return false;
+ }
var carried = new List();
var (top, bottom) = SingleQuotient.OverLeastCommonDenominator(expr, carried);
- if (MultivariatePolynomial.TryParse(top, indices) is not { } parsedTop
- || MultivariatePolynomial.TryParse(bottom, indices) is not { } parsedBottom)
+ if (MultivariatePolynomial.TryParse(top, indices, Monomial.Capacity) is not { } parsedTop)
+ {
+ refusal = TooLarge(top);
return false;
+ }
+ if (MultivariatePolynomial.TryParse(bottom, indices, Monomial.Capacity) is not { } parsedBottom)
+ {
+ refusal = TooLarge(bottom);
+ return false;
+ }
var product = MultivariatePolynomial.One(variableCount);
foreach (var turnedOver in carried)
{
- if (MultivariatePolynomial.TryParse(turnedOver, indices) is not { } parsed
- || product.Multiply(parsed) is not { } next)
+ if (MultivariatePolynomial.TryParse(turnedOver, indices, Monomial.Capacity) is not { } parsed)
+ {
+ refusal = TooLarge(turnedOver);
return false;
+ }
+ if (product.Multiply(parsed) is not { } next)
+ {
+ refusal = new(RationalRefusalKind.Terms, MultivariatePolynomial.MaxTerms);
+ return false;
+ }
product = next;
}
(numerator, denominator, excluded) = (parsedTop, parsedBottom, product);
return true;
}
+
+ ///
+ /// The first part of that is not a number in Q, one of
+ /// the variables, or a sum, difference, product, quotient or whole power of such parts;
+ /// where there is none.
+ ///
+ private static Entity? NotRational(Entity expr, IReadOnlyDictionary indices)
+ => expr switch
+ {
+ Rational => null,
+ Variable variable => indices.ContainsKey(variable) ? null : variable,
+ Sumf(var left, var right) => NotRational(left, indices) ?? NotRational(right, indices),
+ Minusf(var left, var right) => NotRational(left, indices) ?? NotRational(right, indices),
+ Mulf(var left, var right) => NotRational(left, indices) ?? NotRational(right, indices),
+ Divf(var left, var right) => NotRational(left, indices) ?? NotRational(right, indices),
+ Powf(var @base, Integer) => NotRational(@base, indices),
+ _ => expr
+ };
+
+ ///
+ /// Why a polynomial made only of rational parts was not read: an exponent past
+ /// , written or reached by multiplying out,
+ /// or else more terms than .
+ ///
+ private static RationalRefusal TooLarge(Entity polynomial)
+ {
+ var degree = DegreeBound(polynomial, out var variable);
+ return degree > MultivariatePolynomial.MaxDegree
+ ? new(RationalRefusalKind.Degree, degree, variable)
+ : new(RationalRefusalKind.Terms, MultivariatePolynomial.MaxTerms);
+ }
+
+ ///
+ /// The highest power of one variable that multiplying out as
+ /// written reaches, and that variable; a written exponent of a number counts as itself,
+ /// since the parse refuses it as it refuses a degree.
+ ///
+ private static int DegreeBound(Entity node, out Entity? variable)
+ {
+ variable = null;
+ var worst = 0;
+ foreach (var candidate in node.Vars)
+ {
+ var degree = DegreeIn(node, candidate);
+ if (degree > worst)
+ (worst, variable) = (degree, candidate);
+ }
+ foreach (var power in node.Nodes)
+ if (power is Powf(_, Integer exponent) && !exponent.EInteger.Abs().CanFitInInt32())
+ return int.MaxValue;
+ else if (power is Powf(var @base, Integer small) && small.EInteger.Abs().ToInt32Checked() is var magnitude
+ && magnitude > worst && magnitude > MultivariatePolynomial.MaxDegree)
+ (worst, variable) = (magnitude, @base);
+ return worst;
+ }
+
+ private static int DegreeIn(Entity node, Variable variable)
+ => node switch
+ {
+ Variable other => other == variable ? 1 : 0,
+ Sumf(var left, var right) => Math.Max(DegreeIn(left, variable), DegreeIn(right, variable)),
+ Minusf(var left, var right) => Math.Max(DegreeIn(left, variable), DegreeIn(right, variable)),
+ Mulf(var left, var right) => Saturated((long)DegreeIn(left, variable) + DegreeIn(right, variable)),
+ Divf(var left, _) => DegreeIn(left, variable),
+ Powf(var @base, Integer exponent) when exponent.EInteger.Sign > 0 =>
+ exponent.EInteger.CanFitInInt32() ? Saturated((long)DegreeIn(@base, variable) * exponent.EInteger.ToInt32Checked()) : int.MaxValue,
+ _ => 0
+ };
+
+ private static int Saturated(long value) => value > int.MaxValue ? int.MaxValue : (int)value;
+ }
+
+ internal enum RationalRefusalKind
+ {
+ /// There was an answer.
+ None,
+ Complexity,
+ Variables,
+ NotRational,
+ Exponent,
+ Degree,
+ Terms,
+ Divisor,
+ ZeroDenominator,
+ }
+
+ ///
+ /// Why gave no answer: a bound, with
+ /// the value that passed it, or the part that is not a rational function over Q.
+ /// https://github.com/asc-community/AngouriMath/issues/2721
+ ///
+ internal readonly struct RationalRefusal
+ {
+ internal RationalRefusal(RationalRefusalKind kind, int value = 0, Entity? offending = null)
+ => (Kind, Value, Offending) = (kind, value, offending);
+
+ internal RationalRefusalKind Kind { get; }
+
+ internal int Value { get; }
+
+ internal Entity? Offending { get; }
+
+ public override string ToString() => Kind switch
+ {
+ RationalRefusalKind.NotRational => $"not a rational function over Q: {Offending?.Stringize()}",
+ RationalRefusalKind.Complexity => $"complexity {Value}, above the bound of {RationalFunction.MaxComplexity}",
+ RationalRefusalKind.Variables => $"{Value} variables, above the bound of {Monomial.Capacity}",
+ RationalRefusalKind.Exponent => $"a quotient to the power {Value}, above the bound of {RationalFunction.MaxExponent}",
+ RationalRefusalKind.Degree => $"degree {Value} in {Offending?.Stringize()}, above the bound of {MultivariatePolynomial.MaxDegree}",
+ RationalRefusalKind.Terms => $"a polynomial of more than {Value} terms",
+ RationalRefusalKind.Divisor => $"the greatest common divisor passed its bound of {MultivariatePolynomial.MaxIntermediateTerms} intermediate terms or {PolynomialGcd.MaxSteps} steps",
+ RationalRefusalKind.ZeroDenominator => "the denominator is the zero polynomial",
+ _ => ""
+ };
}
}
diff --git a/Sources/AngouriMath/Functions/Continuous/Integration/IndefiniteIntegralSolver.cs b/Sources/AngouriMath/Functions/Continuous/Integration/IndefiniteIntegralSolver.cs
index fa2017aab..98c833a54 100644
--- a/Sources/AngouriMath/Functions/Continuous/Integration/IndefiniteIntegralSolver.cs
+++ b/Sources/AngouriMath/Functions/Continuous/Integration/IndefiniteIntegralSolver.cs
@@ -23180,13 +23180,13 @@ static IEnumerable MonomialDivisors(MultivariatePolynomi
var monomial = term.Monomials.First();
var coefficient = term.CoefficientOf(monomial);
var powers = Enumerable.Range(0, count).Select(v => MultivariatePolynomial.PowerOfMonomial(monomial, v)).ToArray();
- var divisors = new List { 0 };
+ var divisors = new List { Functions.Monomial.One };
for (var v = 0; v < count; v++)
{
- var next = new List();
+ var next = new List();
foreach (var partial in divisors)
for (var k = 0; k <= powers[v]; k++)
- next.Add(partial | (k == 0 ? 0 : MultivariatePolynomial.PackMonomial(v, k)));
+ next.Add(k == 0 ? partial : partial | MultivariatePolynomial.PackMonomial(v, k));
divisors = next;
if (divisors.Count > 256)
yield break;
diff --git a/Sources/AngouriMath/Functions/Continuous/Solvers/InequalitySolver/PolynomialSignTable.cs b/Sources/AngouriMath/Functions/Continuous/Solvers/InequalitySolver/PolynomialSignTable.cs
index e8bde9ddb..4b964628c 100644
--- a/Sources/AngouriMath/Functions/Continuous/Solvers/InequalitySolver/PolynomialSignTable.cs
+++ b/Sources/AngouriMath/Functions/Continuous/Solvers/InequalitySolver/PolynomialSignTable.cs
@@ -286,7 +286,7 @@ private static bool TryRealRootsOf(
return null;
if (!discriminant.IsConstant)
return null;
- var sign = discriminant.CoefficientOf(0).Sign;
+ var sign = discriminant.ConstantCoefficient.Sign;
if (sign == 0)
return null;
switch (degree)
diff --git a/Sources/Tests/UnitTests/Algebra/Polynomials/MultivariateGcdTest.cs b/Sources/Tests/UnitTests/Algebra/Polynomials/MultivariateGcdTest.cs
index f902c85b8..570d1357a 100644
--- a/Sources/Tests/UnitTests/Algebra/Polynomials/MultivariateGcdTest.cs
+++ b/Sources/Tests/UnitTests/Algebra/Polynomials/MultivariateGcdTest.cs
@@ -8,6 +8,7 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
+using System.Linq;
using AngouriMath;
using AngouriMath.Core.Transformations;
using AngouriMath.Extensions;
@@ -439,11 +440,8 @@ public void EqualArgumentsGiveThemselves() =>
AssertGcd("x ^ 2 - y ^ 2", "2 * x ^ 2 - 2 * y ^ 2", "3 * x ^ 2 - 3 * y ^ 2", "x", "y");
///
- /// A ninth variable has no byte in the packed exponent vector, and the shift that
- /// would address it is negative — which the language turns into a shift by 56, the
- /// first variable's byte. Read that way x_1 - x_9 is the zero polynomial, so
- /// the parse is refused instead. Both callers check the count themselves, which is why
- /// this never reached anybody; the refusal is at the door so the next one need not.
+ /// Unless told otherwise the parse reads the eight variables the solvers and the
+ /// integrator ask about, and refuses a ninth for the whole parse.
///
[Fact]
public void MoreVariablesThanFitAreRefused()
@@ -460,6 +458,34 @@ public void MoreVariablesThanFitAreRefused()
Assert.Null(MultivariatePolynomial.TryParse("x_1 + x_2".ToEntity(), Index(nine)));
}
+ ///
+ /// A monomial holds sixteen variables, and the rational canonical form reads that many.
+ /// Past the capacity a variable would have no byte of its own and alias another one's --
+ /// x_1 - x_17 read as the zero polynomial -- so the parse is refused instead.
+ /// https://github.com/asc-community/AngouriMath/issues/2721
+ ///
+ [Fact]
+ public void Issue2721SixteenVariablesFitAndASeventeenthIsRefused()
+ {
+ var names = Enumerable.Range(1, 17).Select(i => $"x_{i}").ToArray();
+ var sixteen = Index(names.Take(16).ToArray());
+ Assert.Equal(16, Monomial.Capacity);
+ Assert.Null(MultivariatePolynomial.TryParse("x_1 - x_9".ToEntity(), Index(names.Take(9).ToArray())));
+
+ foreach (var other in new[] { 2, 8, 9, 15, 16 })
+ {
+ var difference = MultivariatePolynomial.TryParse($"x_1 - x_{other}".ToEntity(), sixteen, Monomial.Capacity);
+ Assert.True(difference is { IsZero: false, TermCount: 2 }, $"x_1 - x_{other}");
+ }
+ Assert.Null(MultivariatePolynomial.TryParse("x_1 - x_17".ToEntity(), Index(names), Monomial.Capacity));
+
+ // The arithmetic carries the second word: the gcd of two products sharing x_9 x_16.
+ var left = MultivariatePolynomial.TryParse("(x_9 * x_16 + x_1) * (x_2 - x_12)".ToEntity(), sixteen, Monomial.Capacity)!;
+ var right = MultivariatePolynomial.TryParse("(x_9 * x_16 + x_1) * (x_3 + x_10 ^ 2)".ToEntity(), sixteen, Monomial.Capacity)!;
+ var expected = MultivariatePolynomial.TryParse("x_9 * x_16 + x_1".ToEntity(), sixteen, Monomial.Capacity)!;
+ Assert.True(PolynomialGcd.Gcd(left, right, Enumerable.Range(0, 16).ToArray(), 0)?.SameAs(expected) is true);
+ }
+
///
/// Half of what a byte holds is the most one exponent may carry if the sum of two is
/// to stay in the byte, so the cap is 127 and going past it is a refusal, not a wrap.
diff --git a/Sources/Tests/UnitTests/Common/PublicApi.txt b/Sources/Tests/UnitTests/Common/PublicApi.txt
index 0d2b7db93..d9f135a09 100644
--- a/Sources/Tests/UnitTests/Common/PublicApi.txt
+++ b/Sources/Tests/UnitTests/Common/PublicApi.txt
@@ -483,6 +483,7 @@ AngouriMath.Core.Transformations.TransformationResult.Changed { } : System.Boole
AngouriMath.Core.Transformations.TransformationResult.Input { } : AngouriMath.Entity
AngouriMath.Core.Transformations.TransformationResult.Output { } : AngouriMath.Entity
AngouriMath.Core.Transformations.TransformationResult.OutputOrInput { } : AngouriMath.Entity
+AngouriMath.Core.Transformations.TransformationResult.Refusal { } : System.String
AngouriMath.Core.Transformations.TransformationResult.Relation { } : AngouriMath.Core.Transformations.TransformationRelation
AngouriMath.Core.Transformations.TransformationResult.Soundness { } : AngouriMath.Core.Transformations.Soundness
AngouriMath.Core.Transformations.TransformationResult.Succeeded { } : System.Boolean
diff --git a/Sources/Tests/UnitTests/Core/Transformations/RationalCanonicalFormTest.cs b/Sources/Tests/UnitTests/Core/Transformations/RationalCanonicalFormTest.cs
index bb6c38aac..49b8aa39d 100644
--- a/Sources/Tests/UnitTests/Core/Transformations/RationalCanonicalFormTest.cs
+++ b/Sources/Tests/UnitTests/Core/Transformations/RationalCanonicalFormTest.cs
@@ -8,6 +8,7 @@
using AngouriMath;
using AngouriMath.Core.Transformations;
using AngouriMath.Extensions;
+using System.Linq;
using Xunit;
namespace AngouriMath.Tests.Core.Transformations
@@ -204,6 +205,93 @@ public void TheValueIsUnchanged(string expression)
Assert.Equal(Entity.Number.Integer.Create(0), difference);
}
+ private static Entity Bare(Entity expression)
+ {
+ while (expression is Entity.Providedf(var inner, _)) expression = inner;
+ return expression;
+ }
+
+ /// One rational function in nine variables, with a variable to be named.
+ private const string Issue2721Shape
+ = "n / (a^2 * (m + n) * n - (a * c * n)^2) * (n * w^2 * S + u)"
+ + " + n * a * c / (a^2 * (m + n) * n - (a * c * n)^2) * (a * v^2 * S + r)";
+
+ ///
+ /// Nine variables have a form as eight do, and it does not depend on what one of them is
+ /// called: written with x, which sorts after u, v and w, and
+ /// renamed back to t, which sorts before them, it is the form of the expression
+ /// written with t. Eight was the most a packed monomial held.
+ /// https://github.com/asc-community/AngouriMath/issues/2721
+ ///
+ [Theory]
+ [InlineData("b")]
+ [InlineData("t")]
+ [InlineData("x")]
+ [InlineData("z")]
+ [InlineData("theta_1")]
+ public void Issue2721NineVariablesHaveAFormWhateverTheyAreCalled(string name)
+ {
+ var written = Required(Issue2721Shape.Replace("S", name));
+ var withT = Required(Issue2721Shape.Replace("S", "t"));
+ var renamedBack = Bare(written).Substitute(MathS.Var(name), MathS.Var("t"));
+ Assert.Equal(Bare(withT), Bare(Required(renamedBack.Stringize())));
+ Assert.Equal(withT is Entity.Providedf(_, var condition) ? condition : null,
+ written is Entity.Providedf(_, var conditionToo) ? conditionToo : null);
+ }
+
+ ///
+ /// Sixteen variables is what a monomial holds, and the bound is a refusal past it. The
+ /// sum cancels x_1 + x_16 and gathers the rest over one denominator.
+ /// https://github.com/asc-community/AngouriMath/issues/2721
+ ///
+ [Fact]
+ public void Issue2721SixteenVariablesHaveAFormAndSeventeenAreRefused()
+ {
+ static string Sum(int from, int to)
+ => string.Join(" + ", System.Linq.Enumerable.Range(from, to - from + 1).Select(i => $"x_{i}"));
+ var sixteen = $"(x_1 + x_16) * ({Sum(2, 8)}) / ((x_1 + x_16) * x_2 * x_3) + ({Sum(9, 15)}) / (x_3 * x_2)";
+ var form = Required(sixteen);
+ Assert.Equal(Required($"({Sum(2, 15)}) / (x_2 * x_3)"), Bare(form));
+ Assert.Null(Canonical($"x_17 / ({Sum(1, 16)}) + 1 / x_1"));
+ }
+
+ ///
+ /// A refusal says why: a bound reached, which one and the value that passed it, or the
+ /// part that is not a rational function over Q. The printed result carries it after the
+ /// input. Seventeen variables is a bound, sin(x) is not a rational function.
+ /// https://github.com/asc-community/AngouriMath/issues/2721
+ ///
+ [Theory]
+ [InlineData("sin(x) / y + 1", "not a rational function over Q: sin(x)")]
+ [InlineData("pi / x + 1 / y", "not a rational function over Q: pi")]
+ [InlineData("(1 / x + 1) ^ 40", "a quotient to the power 40, above the bound of 32")]
+ [InlineData("x ^ 100 * x ^ 100 / y", "degree 200 in x, above the bound of 127")]
+ [InlineData("(a + b + c + d + f + g) ^ 9 / h", "a polynomial of more than 512 terms")]
+ [InlineData("x / (y - y)", "the denominator is the zero polynomial")]
+ public void Issue2721ARefusalSaysWhy(string expression, string refusal)
+ {
+ var result = Transformation.RationalCanonicalization.Apply(expression.ToEntity());
+ Assert.False(result.Succeeded);
+ Assert.Equal(refusal, result.Refusal);
+ Assert.EndsWith(": " + refusal, result.ToString());
+ }
+
+ /// The two bounds checked before anything is read: variables and size.
+ [Fact]
+ public void Issue2721ARefusalForABoundNamesItsValue()
+ {
+ var seventeen = string.Join(" + ", System.Linq.Enumerable.Range(1, 17).Select(i => $"x_{i}")) + " / x_1";
+ Assert.Equal("17 variables, above the bound of 16", Transformation.RationalCanonicalization.Apply(seventeen.ToEntity()).Refusal);
+
+ var large = (Entity)"1 / x";
+ for (var i = 0; i < 60; i++)
+ large += $"x ^ 2 * y + {i}".ToEntity() / "y + 1".ToEntity();
+ var refused = Transformation.RationalCanonicalization.Apply(large);
+ Assert.Equal($"complexity {large.Complexity}, above the bound of 256", refused.Refusal);
+
+ Assert.Null(Transformation.RationalCanonicalization.Apply("1 / x + 1 / y".ToEntity()).Refusal);
+ }
+
/// Nothing applies it behind the caller's back.
[Fact]
public void NothingRunsItByDefault()