Skip to content

Commit ff72b6f

Browse files
Compile a matrix argument as an array, with its inverse and whole powers (#2429)
* Compile a matrix argument as an array, with its inverse and whole powers Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 2eea2e9 commit ff72b6f

10 files changed

Lines changed: 664 additions & 43 deletions

File tree

‎BREAKING-CHANGES.md‎

Lines changed: 66 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1767,17 +1767,76 @@ are now also found wherever the `1` and the square sit in a sum, under the condi
17671767
| `"1 + tan(x)^2 - sec(x)^2".Simplify()` | `1 + tan(x) ^ 2 - sec(x) ^ 2` | `0 provided not cos(x) = 0` |
17681768
| `"a + 1 + tan(y)^2 - sec(y)^2".Simplify()` | `a + 1 + tan(y) ^ 2 - sec(y) ^ 2` | `a provided not cos(y) = 0` |
17691769

1770-
### A scalar over a matrix argument is not compiled
1770+
### A scalar over a matrix argument is the scalar times its inverse
17711771

1772-
**Not silent: what compiled to a wrong value now throws `UncompilableNodeException`.** A scalar over a matrix that is an
1773-
argument of the compiled function was compiled as the scalar over every element, where evaluation takes it as the scalar
1774-
times the inverse. The inverse is not compiled, as a negative matrix power is not, so the quotient is refused. A matrix
1775-
written into the expression is inverted before it is compiled, as before
1776-
([#2287](https://github.com/asc-community/AngouriMath/issues/2287)).
1772+
**Not silent: what compiled to a wrong value now gives the right one.** A scalar over a matrix that is an argument of the
1773+
compiled function was compiled as the scalar over every element, where evaluation takes it as the scalar times the
1774+
inverse. Since 2.6.0 it was refused while the inverse was not compiled
1775+
([#2287](https://github.com/asc-community/AngouriMath/issues/2287)), and the inverse compiles now: a matrix over a matrix is the first times the inverse of the second, and a negative power
1776+
is that power of the inverse, as evaluation has them. A singular matrix's inverse is NaN in every entry, as a compiled
1777+
division by zero has no value. A matrix of `int`, `long` or `BigInteger` is not inverted: its inverse is not a matrix of
1778+
whole numbers. A matrix written into the expression is inverted before it is compiled, as before.
17771779

17781780
| Input | Was (2.6.0) | Now |
17791781
|---|---|---|
1780-
| `"x / A"`, compiled over `GenTensor<double>` and called at `A = [[1, 2], [3, 4]]`, `x = 2` | `[[2, 1], [0.667, 0.5]]` | throws `UncompilableNodeException` |
1782+
| `"x / A"`, compiled over `GenTensor<double>` and called at `A = [[1, 2], [3, 4]]`, `x = 2` | `[[2, 1], [0.667, 0.5]]` | `[[-4, 2], [3, -1]]` |
1783+
| `"A ^ (-1)"`, compiled over `GenTensor<double>` and called at `A = [[1, 2], [3, 4]]` | throws `NotSupportedException` when called | `[[-2, 1], [1.5, -0.5]]` |
1784+
| `"A / B"`, compiled over `GenTensor<double>` | throws `UncompilableNodeException` | `A` times the inverse of `B` |
1785+
1786+
### A compiled matrix power is the matrix power of a whole exponent
1787+
1788+
**Silent: a matrix to a power that is not whole has no compiled value, where 2.6.0 compiled it entry by entry.** In 2.6.0
1789+
simplification raised each entry to the power before compiling, so `[[x, 1], [0, y]] ^ x` compiled as `[[x ^ x, 1], [0,
1790+
y ^ x]]`. Evaluation takes a power of a matrix as a matrix power since "A matrix is divided, raised to a power and compared
1791+
as a matrix" above, and leaves one that is not whole unevaluated. The compiled delegate now takes the matrix power where the
1792+
exponent is whole, and throws `InvalidMatrixOperationException` when called with one that is not; it no longer casts the
1793+
exponent to `int`, which truncates. An exponent of type `Complex` compiles, and is whole where its imaginary part is zero and
1794+
its real part is whole.
1795+
1796+
| Input | Was (2.6.0) | Now |
1797+
|---|---|---|
1798+
| `"[[x, 1], [0, y]] ^ x"`, compiled over `double` to `GenTensor<double>` and called at `(0.7, -1.3)` | `[[0.779, 1], [0, NaN]]`, each entry to the power | throws `InvalidMatrixOperationException` |
1799+
| the same compiled over `Complex` to `GenTensor<Complex>` | throws `UncompilableNodeException` | a delegate; the matrix power at a whole `x`, and `InvalidMatrixOperationException` at any other |
1800+
1801+
### A power of a matrix that is not square is refused when compiling
1802+
1803+
**Not silent: what compiled to a wrong value now throws `InvalidMatrixOperationException`.** In 2.6.0 simplification
1804+
squared `[[x, 1, y]]` entry by entry, and the delegate returned that. A matrix that is not square has no power, and
1805+
evaluation leaves it written. Simplification also leaves written any operation on written matrices whose shapes do not
1806+
fit, and `Compile` now refuses each of them, naming the shapes, rather than building a delegate that throws whenever it is
1807+
called. A matrix argument's shape is known only when the delegate is called, and is checked then.
1808+
1809+
| Input | Was (2.6.0) | Now |
1810+
|---|---|---|
1811+
| `"[[x, 1, y]] ^ 2".ToEntity().Compile<Complex, Complex, GenTensor<Complex>>("x", "y")`, called at `(1, 2)` | `[[1, 1, 4]]` | throws `InvalidMatrixOperationException` when compiling |
1812+
1813+
### A compiled matrix is taken and given as a two-dimensional array, and FastExpression compiles a number made of matrices
1814+
1815+
**Addition, not silent.** Under the LINQ compiler `double[,]`, `Complex[,]`, `float[,]`, `int[,]`, `long[,]` and
1816+
`BigInteger[,]` are matrices, as arguments and as the result, read into and out of the `GenTensor` the arithmetic runs
1817+
on, so a caller need not know GenericTensor. FastExpression simplifies an expression with a matrix in it before
1818+
compiling it, as the LINQ compiler does since [#425](https://github.com/asc-community/AngouriMath/issues/425), so one whose
1819+
value is a number compiles. One whose value is a matrix is refused as before, and the message names the LINQ form.
1820+
1821+
| Input | Was (2.6.0) | Now |
1822+
|---|---|---|
1823+
| `"A * B".ToEntity().Compile<double[,], double[,], double[,]>("A", "B")` | throws `UncompilableNodeException` | the matrix product |
1824+
| `"[1, 0]T * [[a, b], [c, d]] * [0, 1]".ToEntity().Compile("a", "b", "c", "d")` | throws `UncompilableNodeException` | `b` |
1825+
1826+
### A matrix argument is not simplified as a number before compiling
1827+
1828+
**Silent: what compiled to a wrong value now gives the right one.** The LINQ compiler simplifies an expression with a
1829+
written matrix in it before compiling ([#425](https://github.com/asc-community/AngouriMath/issues/425)), and
1830+
simplification reads a variable as a number. With a matrix argument beside the written matrices, `[[1, 0]] * A * [[0], [1]]`
1831+
was multiplied out to `0`, and the delegate returned that whatever `A` was. Only the parts that do not mention a matrix
1832+
argument are simplified now, a written matrix beside a matrix argument is over the argument's element type, and a matrix
1833+
known when compiling to be 1 x 1 compiles as a number, its entry, as evaluation has it.
1834+
1835+
| Input | Was (2.6.0) | Now |
1836+
|---|---|---|
1837+
| `"[[1, 0]] * A * [[0], [1]]"`, compiled from `GenTensor<double>` to `double` and called at `A = [[1, 2], [3, -4]]` | `0` | `2` |
1838+
| `"A + [[1, 2], [3, 4]]"`, compiled over `GenTensor<double>`, the same | throws `UncompilableNodeException` | `[[2, 4], [6, 0]]` |
1839+
| `"[[1, 0]] * A"`, compiled over `GenTensor<double>`, the same | throws `KeyNotFoundException` | `[[1, 2]]` |
17811840

17821841
### A square system is not answered with rows that are no solution
17831842

‎Sources/AngouriMath/Docs/Usage/Exceptions.md‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -169,8 +169,11 @@ the wrappers living in `AngouriMath.Core.Compilation.IntoLinq` — and that is t
169169
to and to pass a matrix in as: `"A * B".ToEntity().Compile<GenTensor<double, DoubleOperations>,
170170
GenTensor<double, DoubleOperations>, GenTensor<double, DoubleOperations>>("A", "B")` is the matrix
171171
product, `2 A + B - 1` scales, adds and shifts element by element, `A ^ 3` is the matrix power
172-
([#526](https://github.com/asc-community/AngouriMath/issues/526)). Compiling a matrix as a
173-
number, or a number as a matrix, or `sin(A)`, is still this exception.
172+
([#526](https://github.com/asc-community/AngouriMath/issues/526)). A two-dimensional array of the
173+
element type -- `double[,]`, `Complex[,]` -- is a matrix too, as an argument and as the result.
174+
Compiling a matrix as a number, or a number as a matrix, or `sin(A)`, is still this exception, and
175+
so is dividing by a matrix of `int`, `long` or `BigInteger`, whose inverse is not one of whole
176+
numbers.
174177

175178
### `CannotEvalException`
176179

@@ -232,6 +235,10 @@ the matrix is not square, `AsScalar` on something that is not 1x1, a tensor of t
232235
dimensions, a row of the wrong width added to a `MatrixBuilder`. The messages name the shapes
233236
involved.
234237

238+
A compiled matrix raises it as well: `Compile` where the shapes of matrices written into the
239+
expression do not fit, and the compiled delegate where the shapes of matrix arguments do not, or
240+
where a matrix power's exponent is not a whole number.
241+
235242
### `BadMatrixShapeException`
236243

237244
The same subject, narrower: matrices being concatenated whose extents disagree along the joining

‎Sources/AngouriMath/Functions/Compilation/IntoFE/Compiler.cs‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,9 @@ private protected override void CompileNode(Compiler compiler) =>
9797
partial record Matrix
9898
{
9999
private protected override void CompileNode(Compiler compiler) =>
100-
throw new UncompilableNodeException($"A {nameof(Matrix)} cannot be compiled: `{Stringize()}`");
100+
throw new UncompilableNodeException(
101+
$"A {nameof(Matrix)} cannot be compiled to a FastExpression, whose value is a number: `{Stringize()}`. "
102+
+ "Compile it with Compile<..., double[,]> or Compile<..., Complex[,]> to have the matrix");
101103
}
102104

103105
// Each function and operator processing
@@ -1020,6 +1022,11 @@ internal static FastExpression Compile(Entity func, IEnumerable<Variable> variab
10201022
varNamespace[varName] = id++;
10211023
foreach (var constant in Variable.NamedConstants.Values)
10221024
func = func.Substitute(constant, constant.Value);
1025+
// An expression built out of matrices often has a number for its value -- [1, 0]T * [[a, b], [c, d]] * [0, 1]
1026+
// is b -- and the LINQ compiler simplifies such an expression first, for that reason. This one did not, and
1027+
// refused it. https://github.com/asc-community/AngouriMath/issues/425
1028+
if (func.Nodes.Any(node => node is Matrix))
1029+
func = func.InnerSimplified;
10231030
func = Compilation.CompiledMembership.Rewritten(func);
10241031
func = Functions.ExponentialQuotients.Rewritten(func);
10251032
Compilation.StatementPositions.Check(func);

‎Sources/AngouriMath/Functions/Compilation/IntoLinq/CompilationProtocol.cs‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,9 +93,12 @@ public virtual Expression ConvertType(Expression expr, Type type)
9393
throw new UncompilableNodeException($"A statement that may have no truth value cannot be compiled as {type}, which has no NaN");
9494
return ConvertType(Expression.Call(ThreeValuedLogic.IversonMethod, ConvertType(expr, typeof(bool?))), type);
9595
}
96+
// A tensor is given back as the two-dimensional array of its element type where that is asked for.
97+
if (TensorCompilation.AsArray(expr, type) is { } array)
98+
return array;
9699
// A tensor converts to nothing but itself: a matrix over one element type is not
97100
// a matrix over another, and it is not a number.
98-
if (TensorCompilation.IsTensor(expr.Type) || TensorCompilation.IsTensor(type))
101+
if (TensorCompilation.IsMatrixType(expr.Type) || TensorCompilation.IsMatrixType(type))
99102
throw new UncompilableNodeException($"A value of type {expr.Type} cannot be compiled as {type}");
100103

101104
bool exprNullable = (Nullable.GetUnderlyingType(expr.Type) is not null) || (expr.Type == typeof(object));

‎Sources/AngouriMath/Functions/Compilation/IntoLinq/IntoLinqCompiler.cs‎

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,17 +22,21 @@ internal static TDelegate Compile<TDelegate>(
2222
IEnumerable<(Type type, Variable variable)> typesAndNames
2323
) where TDelegate : Delegate
2424
{
25+
bool IsMatrixArgument(Variable variable) => typesAndNames.Any(c => c.variable == variable && TensorCompilation.IsMatrixType(c.type));
2526
// A matrix has no compiled form, but an expression built out of matrices often
2627
// has a value that is an ordinary number -- [0, 1]T * [[a, b], [c, d]] * [1, 0]
2728
// is c -- and there is nothing to stop that being compiled. Nothing simplified
2829
// before compiling, so those failed along with the ones that genuinely cannot
2930
// be compiled (https://github.com/asc-community/AngouriMath/issues/425).
3031
// Only expressions that mention a matrix pay for this.
3132
if (expr.Nodes.Any(node => node is Entity.Matrix))
32-
expr = expr.InnerSimplified;
33+
expr = TensorCompilation.SimplifiedAroundMatrixArguments(expr, IsMatrixArgument);
3334
expr = CompiledMembership.Rewritten(expr);
3435
expr = Functions.ExponentialQuotients.Rewritten(expr);
3536
StatementPositions.Check(expr);
37+
// Two matrices whose shapes are written into the expression and do not fit are refused here, rather than by
38+
// a delegate that throws at every point it is called at. https://github.com/asc-community/AngouriMath/issues/526
39+
TensorCompilation.CheckShapes(expr, IsMatrixArgument);
3640
if (MathS.Settings.RefuseNonRealCompilation && returnType is { } real && IsRealType(real)
3741
&& typesAndNames.All(c => IsRealType(c.type)) && !IsRealWhereverDefined(expr, typesAndNames))
3842
throw new UncompilableNodeException(
@@ -42,6 +46,16 @@ internal static TDelegate Compile<TDelegate>(
4246
var functionArguments = subexpressionsCache.Select(c => c.Value).ToArray(); // copying
4347
var localVars = new List<ParameterExpression>();
4448
var variableAssignments = new List<Expression>();
49+
// A matrix passed in as a two-dimensional array is read into the tensor the arithmetic runs on, once.
50+
foreach (var (_, variable) in typesAndNames)
51+
if (subexpressionsCache[variable] is var argument && TensorCompilation.IsMatrixArray(argument.Type))
52+
{
53+
var asTensor = TensorCompilation.FromArrayArgument(argument);
54+
var local = Expression.Variable(asTensor.Type);
55+
localVars.Add(local);
56+
variableAssignments.Add(Expression.Assign(local, asTensor));
57+
subexpressionsCache[variable] = local;
58+
}
4559

4660
// Linq.Expression refuses a mismatch by throwing its own exceptions -- an
4761
// InvalidOperationException for `not x` where x is a double, an ArgumentException
@@ -54,10 +68,21 @@ internal static TDelegate Compile<TDelegate>(
5468
{
5569
// Over Complex a constant is a Complex too, so that a function of it is taken over Complex: as a long,
5670
// sqrt(-1) widened only to double and was NaN. https://github.com/asc-community/AngouriMath/issues/2235
57-
var constantType = typesAndNames.Any(c => c.type == typeof(System.Numerics.Complex)) || returnType == typeof(System.Numerics.Complex)
71+
// A matrix over Complex, as an argument or as the result, is a Complex the same way.
72+
static bool IsComplex(Type? type)
73+
=> type == typeof(System.Numerics.Complex) || (type is not null && TensorCompilation.ElementOfMatrixType(type) == typeof(System.Numerics.Complex));
74+
// Over a matrix argument of one element type, a written matrix beside it is over that type too, so that
75+
// the two combine: [[1, 0]] * A over double is not a matrix of long times a matrix of double.
76+
var matrixElements = typesAndNames.Select(c => TensorCompilation.ElementOfMatrixType(c.type)).OfType<Type>().Distinct().ToList();
77+
var constantType = typesAndNames.Any(c => IsComplex(c.type)) || IsComplex(returnType)
5878
? typeof(System.Numerics.Complex)
59-
: null;
79+
: matrixElements.Count == 1 ? matrixElements[0] : null;
6080
var tree = BuildTree(expr, subexpressionsCache, variableAssignments, localVars, protocol, constantType);
81+
// A matrix known to be 1 x 1 asked for as a number is its entry, as evaluation has it. Any other matrix
82+
// is refused as a number by ConvertType.
83+
if (TensorCompilation.IsTensor(tree.Type) && returnType is not null && !TensorCompilation.IsMatrixType(returnType)
84+
&& TensorCompilation.IsOneByOne(expr, IsMatrixArgument))
85+
tree = TensorCompilation.ToScalar(tree);
6186
var treeWithLocals = Expression.Block(localVars, variableAssignments.Append(tree));
6287
Expression entireExpression = returnType is not null ? protocol.ConvertType(treeWithLocals, returnType) : treeWithLocals;
6388
var finalLambda = Expression.Lambda<TDelegate>(entireExpression, functionArguments);

0 commit comments

Comments
 (0)