Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions BREAKING-CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,44 @@ compiled as a matrix is not read as a number: the operation is compiled on the m
| `"dot(a, b)".Compile<double[], Complex[], Complex>("a", "b")` | throws `UncompilableNodeException`: vectors over `Double` and `Complex` | the scalar product |
| `"dot(a, b)".Compile("a", "b")` | throws `UncompilableNodeException`, asking for a bug report | throws `UncompilableNodeException`: an operand is a number, and `Compile<..., double[]>` takes vectors |

### Over a matrix argument of whole numbers, a constant and a quotient are not whole numbers

**Silent: a truncated value is the value.** `Compile<...>` with a matrix argument over `long`, `int` or `BigInteger`
converted every constant in the expression to that type, so `0.5` was `0`, `1 / 4` was `0` and `pi` was `3`, in the
matrix arithmetic and outside it; and it divided a matrix of whole numbers entry by entry with truncation. A constant is
now converted only where the element type holds it, an integer for the whole numbers, and keeps its own type otherwise,
the matrix it meets widened to that. A quotient of a matrix of whole numbers, and a power of one to a negative constant,
are computed over `double`, as a quotient of two whole numbers already was: `1 / A`, `A / B` and `A ^ (-1)` were
refused, for want of an inverse among the whole numbers, and now compile. What stays whole is still computed over the
whole numbers, exactly. A result that is not whole, asked for as a matrix of whole numbers, is refused rather than
truncated; a matrix power whose exponent is not whole has no value, as over `double`
([#2556](https://github.com/asc-community/AngouriMath/issues/2556)).

`A = [[1, 2], [3, 4]]` and `B = [[-3, 5], [7, -2]]` throughout.

| Input | Was (2.9.0) | Now |
|---|---|---|
| `"trace(A * 0.5)".Compile<long[,], double>("A")`, and over `int[,]` and `BigInteger[,]` | `0` | `2.5` |
| `"trace(A / 2)".Compile<long[,], double>("A")` | `2` | `2.5` |
| `"trace(A) * 0.5".Compile<long[,], double>("A")` | `0` | `2.5` |
| `"trace(pi * A)".Compile<long[,], double>("A")` | `15` | `15.707963267948966` |
| `"trace(sqrt(2) * A)".Compile<long[,], double>("A")` | `5` | `7.0710678118654755` |
| `"det(A / 2)".Compile<long[,], double>("A")` | `-1` | `-0.5` |
| `"trace(A / n)".Compile<long[,], long, double>("A", "n")` at `n = 2` | `2` | `2.5` |
| `"A / 2".Compile<long[,], double[,]>("A")` | throws `UncompilableNodeException`: a matrix over `Int64` | `[[0.5, 1], [1.5, 2]]` |
| `"[[0.5, 1]] * A".Compile<long[,], double[,]>("A")` | throws `UncompilableNodeException`: a matrix over `Int64` | `[[3.5, 5]]` |
| `"A / 2".Compile<long[,], long[,]>("A")` | `[[0, 1], [1, 2]]` | throws `UncompilableNodeException`: a matrix over `Double` |
| `"A * 0.5".Compile<long[,], long[,]>("A")` | `[[0, 0], [0, 0]]` | throws `UncompilableNodeException`: a matrix over `Double` |
| `"[[0.5, 1]] * A".Compile<long[,], long[,]>("A")` | `[[3, 4]]` | throws `UncompilableNodeException`: a matrix over `Double` |
| `"A ^ 0.5".Compile<long[,], long[,]>("A")` | `[[1, 0], [0, 1]]` | throws `InvalidMatrixOperationException` when called: 0.5 is not a whole exponent |
| `"trace(A + 1 / 4)".Compile<long[,], double>("A")` | `5` | `5.5` |
| `"1 / A".Compile<long[,], double[,]>("A")` | throws `UncompilableNodeException`: no inverse of a matrix of whole numbers | the inverse, `[[-2, 1], [1.5, -0.5]]` to rounding |
| `"A ^ (-1)".Compile<long[,], double[,]>("A")` | throws `UncompilableNodeException`: a matrix over `Int64` | the same inverse |
| `"trace(A ^ (-1))".Compile<long[,], double>("A")` | throws `InvalidMatrixOperationException` when called: no inverse of a matrix of whole numbers | `-2.5` to rounding |
| `"A ^ (-1)".Compile<long[,], long[,]>("A")` | throws `InvalidMatrixOperationException` when called: no inverse of a matrix of whole numbers | throws `UncompilableNodeException`: a matrix over `Double` |
| `"A / B".Compile<long[,], long[,], double[,]>("A", "B")` | throws `UncompilableNodeException`: no inverse of a matrix of whole numbers | `[[16, 11], [34, 27]] / 29` to rounding |
| `"1 / A".Compile<long[,], long[,]>("A")` | throws `UncompilableNodeException`: no inverse of a matrix of whole numbers | throws `UncompilableNodeException`: a matrix over `Double` |

---

## 2.9.0 — since 2.8.0
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,8 @@ internal static TDelegate Compile<TDelegate>(
static bool IsComplex(Type? type)
=> type == typeof(System.Numerics.Complex) || (type is not null && TensorCompilation.ElementOfMatrixType(type) == typeof(System.Numerics.Complex));
// Over a matrix argument of one element type, a written matrix beside it is over that type too, so that
// the two combine: [[1, 0]] * A over double is not a matrix of long times a matrix of double.
// the two combine: [[1, 0]] * A over double is not a matrix of long times a matrix of double. A constant
// that type does not hold keeps its own (see Holds).
var matrixElements = typesAndNames.Select(c => TensorCompilation.ElementOfMatrixType(c.type)).OfType<Type>().Distinct().ToList();
var constantType = typesAndNames.Any(c => IsComplex(c.type)) || IsComplex(returnType)
? typeof(System.Numerics.Complex)
Expand Down Expand Up @@ -149,6 +150,21 @@ private static void CheckResultShape(Entity expr, Type? returnType, Func<Variabl
$"`{expr.Stringize()}` is a matrix of {shape.Columns} columns, not a column vector, and cannot be compiled as {returnType}");
}

/// <summary>
/// Whether an entry of <paramref name="type"/> holds <paramref name="number"/>: the whole numbers hold an
/// integer, the reals a real, and the complex numbers any number. A constant is converted to the element type of
/// the matrix arguments only where it does: over a matrix of whole numbers 0.5 was 0 and pi was 3, so
/// <c>trace(A * 0.5)</c> was 0. One that is not held keeps its own type, and a matrix it meets is widened to that.
/// https://github.com/asc-community/AngouriMath/issues/2556
/// </summary>
private static bool Holds(Type type, Number number)
=> number switch
{
Number.Integer => true,
Number.Real => type == typeof(double) || type == typeof(float) || type == typeof(System.Numerics.Complex),
_ => type == typeof(System.Numerics.Complex),
};

private static bool IsRealType(Type type)
=> type == typeof(double) || type == typeof(float) || type == typeof(int) || type == typeof(long)
|| type == typeof(System.Numerics.BigInteger);
Expand Down Expand Up @@ -194,7 +210,7 @@ internal static Expression BuildTree(
? $", which are {string.Join(", ", over)}"
: ", which are none")),

Number when constantType is { } type => protocol.ConvertType(protocol.ConvertConstant(expr), type),
Number number when constantType is { } type && Holds(type, number) => protocol.ConvertType(protocol.ConvertConstant(expr), type),
Entity.Boolean or Number => protocol.ConvertConstant(expr),

IUnaryNode oneArg
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -809,6 +809,12 @@ internal static Expression Build(Entity.Matrix matrix, IReadOnlyList<Expression>
/// </summary>
internal static Expression? Binary(Entity node, Expression left, Expression right, Func<Expression, Type, Expression> convert)
{
// A quotient of whole numbers is computed over double, of matrices as of numbers, and a matrix to a negative
// power is a quotient: over long, A / 2 divided each entry with truncation, and 1 / A and A ^ (-1) were refused
// for want of an inverse. A power whose exponent arrives only at the call is compiled over the whole numbers,
// where a negative one is refused then. https://github.com/asc-community/AngouriMath/issues/2556
if (node is Entity.Divf || node is Entity.Powf { Exponent: var exponent } && IsNegativeConstant(exponent))
(left, right) = (OverAField(left, convert), OverAField(right, convert));
var leftTensor = kitsByTensor.TryGetValue(left.Type, out var leftKit);
var rightTensor = kitsByTensor.TryGetValue(right.Type, out var rightKit);
if (leftTensor && rightTensor)
Expand Down Expand Up @@ -857,6 +863,13 @@ internal static Expression Build(Entity.Matrix matrix, IReadOnlyList<Expression>
};
}

// A matrix over the whole numbers, which have no quotients, widened to double, which has them; anything else as it is.
private static Expression OverAField(Expression operand, Func<Expression, Type, Expression> convert)
=> kitsByTensor.TryGetValue(operand.Type, out var kit) && kit.Inverse is null ? Widen(operand, typeof(double), convert) : operand;

private static bool IsNegativeConstant(Entity exponent)
=> exponent.Vars.Count == 0 && exponent.Evaled is Entity.Number.Real { IsNegative: true };

// The exponent of a matrix power as the whole number it must be, checked when the delegate is called: over the
// complex numbers a constant is complex too, and it was refused for want of a conversion to int.
private static Expression Exponent(Expression exponent, Func<Expression, Type, Expression> convert)
Expand Down
126 changes: 123 additions & 3 deletions Sources/Tests/UnitTests/Common/CompileMatrixTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -239,17 +239,137 @@ public void ASingularMatrixHasNoInverse()
Assert.All(overComplex.Cast<Complex>(), entry => Assert.True(double.IsNaN(entry.Real)));
}

// The inverse of a matrix of whole numbers is not one: refused where it is written, and at the call where a
// negative exponent arrives there.
// The inverse of a matrix of whole numbers is computed over double, as a quotient of two whole numbers is, and is
// not a matrix of whole numbers: asked for as one, it is refused. A negative exponent that arrives only at the
// call finds the power compiled over the whole numbers, and has no inverse there.
[Fact]
public void AMatrixOfWholeNumbersIsNotInverted()
public void TheInverseOfAMatrixOfWholeNumbersIsNotWhole()
{
Assert.Throws<UncompilableNodeException>(() => "1 / A".ToEntity().Compile<long[,], long[,]>("A"));
Assert.Throws<UncompilableNodeException>(() => "A ^ (-1)".ToEntity().Compile<long[,], long[,]>("A"));
var power = "A ^ n".ToEntity().Compile<long[,], long, long[,]>("A", "n");
Assert.Equal(new long[,] { { 1, 4 }, { 0, 1 } }, power(new long[,] { { 1, 2 }, { 0, 1 } }, 2));
Assert.Throws<InvalidMatrixOperationException>(() => power(new long[,] { { 1, 2 }, { 0, 1 } }, -1));
}

private static Complex[,] AsComplex<T>(T[,] a, Func<T, Complex> entry)
{
var result = new Complex[a.GetLength(0), a.GetLength(1)];
for (var r = 0; r < a.GetLength(0); r++)
for (var c = 0; c < a.GetLength(1); c++)
result[r, c] = entry(a[r, c]);
return result;
}

private static void Near(Complex expected, Complex actual, string where)
=> Assert.True(Complex.Abs(expected - actual) <= 1e-9 * Math.Max(1, Complex.Abs(expected)), $"{where}: expected {expected}, compiled {actual}");

private static readonly long[][,] WholeMatrices =
{
new long[,] { { 1, 2 }, { 3, 4 } },
new long[,] { { -3, 5 }, { 7, -2 } },
};

// A matrix argument over the whole numbers is computed over them only where the value stays whole. A constant
// was converted to the matrix's element type, so 0.5 was 0, pi 3 and sqrt(2) 2 ^ 0; and a quotient divided each
// entry with truncation, where a quotient of two whole numbers is computed over double. trace(A * 0.5) was 0 and
// trace(A / 2) was 2 at A = [[1, 2], [3, 4]], where both are 2.5. Checked against evaluation with A substituted,
// over long, int and BigInteger.
[Theory]
[InlineData("trace(A * 0.5)")]
[InlineData("trace(0.5 * A)")]
[InlineData("trace(A / 2)")]
[InlineData("trace(A / 3)")]
[InlineData("det(A / 2)")]
[InlineData("(A / 2)[2, 1]")]
[InlineData("trace(A) * 0.5")]
[InlineData("trace(pi * A)")]
[InlineData("trace(sqrt(2) * A)")]
[InlineData("[[0.5, 1]] * A * [[1], [0]]")]
[InlineData("trace(A + 1 / 4)")]
[InlineData("trace(1 / A)")]
[InlineData("trace(A ^ (-1))")]
[InlineData("det(A ^ (-2))")]
[InlineData("trace(2 / A + A / 4)")]
public void ANumberOfAMatrixOfWholeNumbersAgreesWithEvaluation(string expression)
{
var e = expression.ToEntity();
var overLongs = e.Compile<long[,], double>("A");
var overInts = e.Compile<int[,], double>("A");
var overBigIntegers = e.Compile<BigInteger[,], double>("A");
foreach (var a in WholeMatrices)
{
var expected = e.Substitute("A", AsEntity(AsComplex(a, v => v))).Evaled.EvalNumerical().ToNumerics();
Near(expected, overLongs(a), $"long, A = {AsEntity(AsComplex(a, v => v))}");
Near(expected, overInts(AsInts(a)), $"int, A = {AsEntity(AsComplex(a, v => v))}");
Near(expected, overBigIntegers(AsBigIntegers(a)), $"BigInteger, A = {AsEntity(AsComplex(a, v => v))}");
}
}

private static int[,] AsInts(long[,] a)
{
var result = new int[a.GetLength(0), a.GetLength(1)];
for (var r = 0; r < a.GetLength(0); r++)
for (var c = 0; c < a.GetLength(1); c++)
result[r, c] = checked((int)a[r, c]);
return result;
}

private static BigInteger[,] AsBigIntegers(long[,] a)
{
var result = new BigInteger[a.GetLength(0), a.GetLength(1)];
for (var r = 0; r < a.GetLength(0); r++)
for (var c = 0; c < a.GetLength(1); c++)
result[r, c] = a[r, c];
return result;
}

// The same, where the value is a matrix: it is a matrix over double. "A / 2" over long[,] asked for as double[,]
// was refused, the quotient being a matrix over long, and [[0.5, 1]] * A was [[3, 4]].
[Theory]
[InlineData("A / 2")]
[InlineData("A * 0.5 + 1")]
[InlineData("[[0.5, 1]] * A")]
[InlineData("1 / A")]
[InlineData("A ^ (-1)")]
[InlineData("A / 4 - 2 / A")]
public void AMatrixOfWholeNumbersAgreesWithEvaluation(string expression)
{
var e = expression.ToEntity();
var overLongs = e.Compile<long[,], double[,]>("A");
foreach (var a in WholeMatrices)
AssertAgrees(Evaluated(e, ("A", AsEntity(AsComplex(a, v => v)))), AsComplex(overLongs(a)));
}

// A quotient of two matrices of whole numbers, and of one by a whole number passed in, is computed over double
// as the quotient by a constant is.
[Fact]
public void AQuotientOfArgumentsOverTheWholeNumbersAgreesWithEvaluation()
{
var (a, b) = (WholeMatrices[0], WholeMatrices[1]);
var (entityA, entityB) = (AsEntity(AsComplex(a, v => v)), AsEntity(AsComplex(b, v => v)));
var quotient = "A / B".ToEntity();
AssertAgrees(Evaluated(quotient, ("A", entityA), ("B", entityB)), AsComplex(quotient.Compile<long[,], long[,], double[,]>("A", "B")(a, b)));
var byANumber = "trace(A / n)".ToEntity();
Near(byANumber.Substitute("A", entityA).Substitute("n", 2).Evaled.EvalNumerical().ToNumerics(),
byANumber.Compile<long[,], long, double>("A", "n")(a, 2), "trace(A / n) at n = 2");
}

// What stays whole is still computed over the whole numbers, exactly, where a double would round: 2 A + 1 at an
// entry of 2 ^ 60 is 2 ^ 61 + 1, which a double does not hold. A quotient or a constant that is not whole, asked
// for as a matrix of whole numbers, is refused rather than truncated; a power that is not whole has no value, as
// over double, where 0.5 was a whole exponent of 0 and A ^ 0.5 was the identity.
[Fact]
public void AMatrixOfWholeNumbersStaysWholeWhereItIs()
{
var a = new long[,] { { 1L << 60, 1 }, { 0, 1 } };
Assert.Equal(new long[,] { { (1L << 61) + 1, 3 }, { 1, 3 } }, "2 A + 1".ToEntity().Compile<long[,], long[,]>("A")(a));
Assert.Equal((1L << 60) + 1, "trace(A)".ToEntity().Compile<long[,], long>("A")(a));
Assert.Throws<UncompilableNodeException>(() => "A / 2".ToEntity().Compile<long[,], long[,]>("A"));
Assert.Throws<UncompilableNodeException>(() => "A * 0.5".ToEntity().Compile<long[,], long[,]>("A"));
Assert.Throws<InvalidMatrixOperationException>(() => "A ^ 0.5".ToEntity().Compile<long[,], long[,]>("A")(WholeMatrices[0]));
}

// A row times a matrix argument times a column is a 1 x 1 matrix, an entry of A, and a number. Simplified before
// compiling with A read as a number, [[1, 0]] * A * [[0], [1]] was multiplied out to 0, which the delegate returned
// whatever A was. Only the parts with no matrix argument are simplified.
Expand Down
Loading