Skip to content

Commit 5de0e67

Browse files
Compile a function of a matrix argument as the function of each entry, and vectors as arrays (#2435)
* Compile a function of a matrix argument as the function of each entry, and vectors as arrays Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 376164d commit 5de0e67

10 files changed

Lines changed: 814 additions & 25 deletions

File tree

‎BREAKING-CHANGES.md‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1873,6 +1873,27 @@ value is a number compiles. One whose value is a matrix is refused as before, an
18731873
| `"A * B".ToEntity().Compile<double[,], double[,], double[,]>("A", "B")` | throws `UncompilableNodeException` | the matrix product |
18741874
| `"[1, 0]T * [[a, b], [c, d]] * [0, 1]".ToEntity().Compile("a", "b", "c", "d")` | throws `UncompilableNodeException` | `b` |
18751875

1876+
### A function of a compiled matrix argument is the function of each entry
1877+
1878+
**Addition, not silent.** Under the LINQ compiler a function of a matrix argument compiles to what evaluation makes of
1879+
it once the matrix is put in: the function of each entry. That holds for a function of one argument, `sin(A)`, `exp(A)`,
1880+
`ln(A)`, `abs(A)`, and of two where evaluation maps it over a matrix and a number or two matrices of one shape: a number
1881+
to the power of a matrix, `log`, `max`, `min`, `mod`, `binomial` and the rest. It is not the matrix function: `exp(A)` is
1882+
not the matrix exponential, which evaluation does not compute either. A power with a matrix for its base stays the
1883+
matrix power. `abs` of a vector, a column or a row known when compiling to be one, is its norm, `sqrt(sum |v_k|^2)`, a
1884+
number ([#2423](https://github.com/asc-community/AngouriMath/issues/2423)); of a two-dimensional array whose shape is known
1885+
only at the call it is the modulus of each entry, and a column or a row of more than one entry there throws
1886+
`InvalidMatrixOperationException`. A matrix
1887+
of statements, as `A < 0` is, has no compiled form. A one-dimensional array, `double[]` or `Complex[]`, is a column
1888+
vector, as an argument and as the result.
1889+
1890+
| Input | Was (2.6.0) | Now |
1891+
|---|---|---|
1892+
| `"sin(A)"`, compiled over `GenTensor<double>` and called at `A = [[1, 2], [3, -4]]` | throws `UncompilableNodeException` | `[[0.841, 0.909], [0.141, 0.757]]` |
1893+
| `"exp(A)"`, `"2 ^ A"`, `"max(A, 0)"`, the same | throws `UncompilableNodeException` | the function of each entry |
1894+
| `"abs(v)"`, compiled from `double[]` to `double` and called at `[3, -4]` | throws `AngouriBugException` | `5` |
1895+
| `"sin(v)"`, compiled from `double[]` to `double[]` | throws `KeyNotFoundException` | the sine of each entry |
1896+
18761897
### A matrix argument is not simplified as a number before compiling
18771898

18781899
**Silent: what compiled to a wrong value now gives the right one.** The LINQ compiler simplifies an expression with a

‎Sources/.editorconfig‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -429,6 +429,9 @@ file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed
429429
[AngouriMath/Functions/Compilation/IntoLinq/TensorCompilation.cs]
430430
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
431431

432+
[AngouriMath/Functions/Compilation/IntoLinq/TensorCompilation.Elementwise.cs]
433+
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
434+
432435
[AngouriMath/Functions/Compilation/IntoLinq/ThreeValuedLogic.cs]
433436
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
434437

@@ -495,6 +498,9 @@ file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed
495498
[Tests/UnitTests/Common/CompileMatrixTest.cs]
496499
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
497500

501+
[Tests/UnitTests/Common/CompileAFunctionOfAMatrixTest.cs]
502+
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
503+
498504
[AngouriMath/Functions/IntervalArithmetic.cs]
499505
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
500506

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

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ take.
154154

155155
`Compile` was asked for a function it cannot build. Two distinct causes, and the message says which:
156156

157-
- a node with no compiled form — a derivative, an integral, a limit, a function of a matrix;
157+
- a node with no compiled form — a derivative, an integral, a limit, a comparison of a matrix;
158158
- a variable the expression mentions that the compilation was not given. The message names the
159159
variable and lists the ones it *was* given, since `Compile("x")` on `a * x` failing used to
160160
surface as a bare `KeyNotFoundException` about some dictionary.
@@ -170,10 +170,13 @@ to and to pass a matrix in as: `"A * B".ToEntity().Compile<GenTensor<double, Dou
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
172172
([#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.
173+
element type -- `double[,]`, `Complex[,]` -- is a matrix too, as an argument and as the result,
174+
and a one-dimensional array -- `double[]` -- is a column vector. A function of a matrix is the
175+
function of each entry, as evaluation has it: `sin(A)`, `exp(A)`, `2 ^ A`, `log(2, A)`,
176+
`max(A, B)`; `abs` of a vector, a column or a row, is its norm. Compiling a matrix as a number, unless it is known
177+
to be 1 x 1, or a number as a matrix, is still this exception, as are a comparison or equality
178+
of matrices, a matrix to the power of a matrix, and dividing by a matrix of `int`, `long` or
179+
`BigInteger`, whose inverse is not one of whole numbers.
177180

178181
### `CannotEvalException`
179182

@@ -237,7 +240,10 @@ involved.
237240

238241
A compiled matrix raises it as well: `Compile` where the shapes of matrices written into the
239242
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.
243+
where a matrix power's exponent is not a whole number. So does a delegate given an empty array, one
244+
returning a vector that is given a matrix of more than one column, and one taking `abs` of a
245+
two-dimensional array that turns out to be a column or a row, whose modulus is a norm rather than a
246+
matrix: pass a column as a one-dimensional array for its norm.
241247

242248
### `BadMatrixShapeException`
243249

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

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -134,11 +134,10 @@ public virtual Expression ConvertType(Expression expr, Type type)
134134
public virtual Expression ConvertUnaryNode(Expression e, Entity typeHolder)
135135
{
136136
e = NumericOperand(e);
137-
// A function of a matrix has no compiled form here: the tensor operations are the
138-
// arithmetic ones, and sin(A) is not an element-by-element sine of a matrix.
137+
// A function of a matrix is the function of each entry, which is what evaluation makes of it, and not a
138+
// matrix function: sin(A) is not the power series of A. https://github.com/asc-community/AngouriMath/issues/526
139139
if (TensorCompilation.IsTensor(e.Type))
140-
throw new UncompilableNodeException(
141-
$"There is no compiled form for {typeHolder.GetType().Name} of a matrix.");
140+
return TensorCompilation.ElementwiseUnary(e, typeHolder, entry => ConvertUnaryNode(entry, typeHolder), ConvertType);
142141
return typeHolder switch
143142
{
144143
Sinf when ShouldBeAtLeastDouble(e) is var newE => Expression.Call(GetDef("Sin", 1, newE.Type), newE),
@@ -238,9 +237,15 @@ public virtual Expression ConvertBinaryNode(Expression left, Expression right, E
238237
// A matrix in either place: the tensor operation of the same name, the scalar side
239238
// converted to the element type. https://github.com/asc-community/AngouriMath/issues/526
240239
if (TensorCompilation.IsTensor(left.Type) || TensorCompilation.IsTensor(right.Type))
240+
{
241+
// A matrix of whole numbers written beside a matrix argument over double is a matrix over double.
242+
(left, right) = TensorCompilation.Widened(left, right, ConvertType);
241243
return TensorCompilation.Binary(typeHolder, left, right, ConvertType)
244+
// A function of two arguments one of which is a matrix, where evaluation applies it entry by entry.
245+
?? TensorCompilation.ElementwiseBinary(typeHolder, left, right, (l, r) => ConvertBinaryNode(l, r, typeHolder), ConvertType)
242246
?? throw new UncompilableNodeException(
243247
$"The node of type {typeHolder.GetType()} has no compiled form over a matrix.");
248+
}
244249

245250
(left, right) = EqualizeTypesIfAble(NumericOperand(left), NumericOperand(right));
246251
return typeHolder switch

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

Lines changed: 46 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ internal static TDelegate Compile<TDelegate>(
2323
) where TDelegate : Delegate
2424
{
2525
bool IsMatrixArgument(Variable variable) => typesAndNames.Any(c => c.variable == variable && TensorCompilation.IsMatrixType(c.type));
26+
Type? TypeOf(Variable variable) => typesAndNames.FirstOrDefault(c => c.variable == variable).type;
2627
// A matrix has no compiled form, but an expression built out of matrices often
2728
// has a value that is an ordinary number -- [0, 1]T * [[a, b], [c, d]] * [1, 0]
2829
// is c -- and there is nothing to stop that being compiled. Nothing simplified
@@ -36,7 +37,9 @@ internal static TDelegate Compile<TDelegate>(
3637
StatementPositions.Check(expr);
3738
// Two matrices whose shapes are written into the expression and do not fit are refused here, rather than by
3839
// a delegate that throws at every point it is called at. https://github.com/asc-community/AngouriMath/issues/526
39-
TensorCompilation.CheckShapes(expr, IsMatrixArgument);
40+
Func<Variable, (int Rows, int Columns)?> argumentShape = variable => TensorCompilation.ShapeOfArgument(TypeOf(variable));
41+
TensorCompilation.CheckShapes(expr, argumentShape);
42+
CheckResultShape(expr, returnType, argumentShape);
4043
if (MathS.Settings.RefuseNonRealCompilation && returnType is { } real && IsRealType(real)
4144
&& typesAndNames.All(c => IsRealType(c.type)) && !IsRealWhereverDefined(expr, typesAndNames))
4245
throw new UncompilableNodeException(
@@ -77,11 +80,15 @@ static bool IsComplex(Type? type)
7780
var constantType = typesAndNames.Any(c => IsComplex(c.type)) || IsComplex(returnType)
7881
? typeof(System.Numerics.Complex)
7982
: matrixElements.Count == 1 ? matrixElements[0] : null;
83+
// Only a matrix argument can be a vector whose shape is not written out: abs of a written one is its norm
84+
// after simplification already.
85+
if (typesAndNames.Any(c => TensorCompilation.IsMatrixType(c.type)))
86+
BuildNorms(expr, argumentShape, subexpressionsCache, variableAssignments, localVars, protocol, constantType);
8087
var tree = BuildTree(expr, subexpressionsCache, variableAssignments, localVars, protocol, constantType);
8188
// A matrix known to be 1 x 1 asked for as a number is its entry, as evaluation has it. Any other matrix
8289
// is refused as a number by ConvertType.
8390
if (TensorCompilation.IsTensor(tree.Type) && returnType is not null && !TensorCompilation.IsMatrixType(returnType)
84-
&& TensorCompilation.IsOneByOne(expr, IsMatrixArgument))
91+
&& TensorCompilation.IsOneByOne(expr, argumentShape))
8592
tree = TensorCompilation.ToScalar(tree);
8693
var treeWithLocals = Expression.Block(localVars, variableAssignments.Append(tree));
8794
Expression entireExpression = returnType is not null ? protocol.ConvertType(treeWithLocals, returnType) : treeWithLocals;
@@ -98,6 +105,43 @@ or NotSupportedException
98105
}
99106
}
100107

108+
/// <summary>
109+
/// Every <c>abs</c> of a column vector, compiled to its norm ahead of the rest and cached, so that the tree
110+
/// built after it reads the number. Of a vector, <c>abs</c> is a number, and of any other matrix a matrix,
111+
/// and only the shape known when compiling can tell which.
112+
/// https://github.com/asc-community/AngouriMath/issues/2423
113+
/// </summary>
114+
private static void BuildNorms(Entity expr, Func<Variable, (int Rows, int Columns)?> argumentShape,
115+
Dictionary<Entity, ParameterExpression> cachedSubexpressions, List<Expression> variableAssignments,
116+
List<ParameterExpression> newLocalVars, CompilationProtocol protocol, Type? constantType)
117+
{
118+
foreach (var norm in TensorCompilation.Norms(expr, argumentShape))
119+
{
120+
if (cachedSubexpressions.ContainsKey(norm))
121+
continue;
122+
var vector = BuildTree(norm.Argument, cachedSubexpressions, variableAssignments, newLocalVars, protocol, constantType);
123+
if (!TensorCompilation.IsTensor(vector.Type))
124+
continue;
125+
var value = Expression.Variable(typeof(double));
126+
variableAssignments.Add(Expression.Assign(value, TensorCompilation.Norm(vector)));
127+
newLocalVars.Add(value);
128+
cachedSubexpressions[norm] = value;
129+
}
130+
}
131+
132+
/// <summary>
133+
/// A matrix known when compiling not to be a column, asked for as a vector, is refused then rather than by a
134+
/// delegate that throws at every call.
135+
/// </summary>
136+
private static void CheckResultShape(Entity expr, Type? returnType, Func<Variable, (int Rows, int Columns)?> argumentShape)
137+
{
138+
if (returnType is null || !TensorCompilation.IsVectorArray(returnType) || TensorCompilation.Shape(expr, argumentShape) is not { } shape)
139+
return;
140+
if (shape.Columns > 1)
141+
throw new InvalidMatrixOperationException(
142+
$"`{expr.Stringize()}` is a matrix of {shape.Columns} columns, not a column vector, and cannot be compiled as {returnType}");
143+
}
144+
101145
private static bool IsRealType(Type type)
102146
=> type == typeof(double) || type == typeof(float) || type == typeof(int) || type == typeof(long)
103147
|| type == typeof(System.Numerics.BigInteger);

0 commit comments

Comments
 (0)