diff --git a/BREAKING-CHANGES.md b/BREAKING-CHANGES.md index 65fc7fa60..bfed8554e 100644 --- a/BREAKING-CHANGES.md +++ b/BREAKING-CHANGES.md @@ -103,6 +103,40 @@ checked by exact division. `Entity.Factorize` asks the same layer. | `MathS.Polynomials.Factor("(x ^ 3 - 5 * x ^ 2 * y ^ 2) * (3 * x ^ 2 + x * y ^ 3 * z ^ 3 - 3 * y ^ 2) * (x - y ^ 3 * z ^ 2 - 5 * y * z ^ 2)", "x")` | `null` | `x ^ 2 * (x - 5 * y ^ 2) * (x - y ^ 3 * z ^ 2 - 5 * y * z ^ 2) * (3 * x ^ 2 + x * y ^ 3 * z ^ 3 - 3 * y ^ 2)` | | `"3 * x ^ 6 + (-3) * x ^ 5 * y ^ 3 * z ^ 2 + (-15) * x ^ 5 * y * z ^ 2 + x ^ 5 * y ^ 3 * z ^ 3 + -x ^ 4 * y ^ 6 * z ^ 5 + (-5) * x ^ 4 * y ^ 4 * z ^ 5 + (-3) * x ^ 4 * y ^ 2 + 3 * x ^ 3 * y ^ 5 * z ^ 2 + 15 * x ^ 3 * y ^ 3 * z ^ 2 + (-15) * x ^ 5 * y ^ 2 + 15 * x ^ 4 * y ^ 5 * z ^ 2 + 75 * x ^ 4 * y ^ 3 * z ^ 2 + (-5) * x ^ 4 * y ^ 5 * z ^ 3 + 5 * x ^ 3 * y ^ 8 * z ^ 5 + 25 * x ^ 3 * y ^ 6 * z ^ 5 + 15 * x ^ 3 * y ^ 4 + (-15) * x ^ 2 * y ^ 7 * z ^ 2 + (-75) * x ^ 2 * y ^ 5 * z ^ 2".Factorize()` | `x ^ 2 * z ^ 2 * ((-15) * y ^ 7 + (-75) * y ^ 5) + x ^ 3 * (z ^ 5 * (5 * y ^ 8 + 25 * y ^ 6) + z ^ 2 * (3 * y ^ 5 + 15 * y ^ 3) + 15 * y ^ 4) + x ^ 4 * (z ^ 2 * (15 * y ^ 5 + 75 * y ^ 3) + z ^ 5 * (-y ^ 6 + (-5) * y ^ 4) + (-3) * y ^ 2 + (-5) * y ^ 5 * z ^ 3) + x ^ 5 * (z ^ 2 * ((-3) * y ^ 3 + (-15) * y) + (y * z) ^ 3 + (-15) * y ^ 2) + 3 * x ^ 6` | `x ^ 2 * (x - 5 * y ^ 2) * (x - y ^ 3 * z ^ 2 - 5 * y * z ^ 2) * (3 * x ^ 2 + x * y ^ 3 * z ^ 3 - 3 * y ^ 2)` | +### A scalar product, a determinant or a transpose of a name compiled as a number is compiled + +**Not silent where it was refused: it compiles, or is refused saying why. Silent where it compiled: a truncated value +or a 0 is the value.** `dot`, `cross`, `det`, `transpose`, `trace` and an entry `A[k, l]` of an expression with a name +beside a written matrix, as in `dot([0, 0, 1], cos(p) * [x, y, z])`, are nodes that simplification leaves as written, +since the name may stand for a matrix. A variable compiled as a number is one, so both compilers now carry each of them +out on the vector or the matrix the expression is with its names as numbers. `Compile(params Variable[])`, whose +variables are all numbers, had no form for these nodes and refused them, asking for a bug report. `Compile<...>` +converted a `double` beside a written matrix of whole numbers, or beside a matrix argument over `long`, to `long`, and +so truncated it; it now widens the matrix instead, as it already widened the narrower of two matrices, and `dot` and +`cross` of vectors over two element types widen the same way. Both compilers read a transpose beside a written matrix +as a number, and multiplied it out to 0, and refused a vector product beside one; a transpose or a product taken of a +number has no value, and is now refused for that reason. A name +compiled as a matrix is not read as a number: the operation is compiled on the matrix passed in, as before +([#105](https://github.com/asc-community/AngouriMath/issues/105)). + +| Input | Was (2.9.0) | Now | +|---|---|---| +| `"dot([0, 0, 1], cos(p) * [x, y, z] + sin(p) / abs([a, b, c]) * cross([a, b, c], [x, y, z]))".Compile("a", "b", "c", "p", "x", "y", "z")` | throws `UncompilableNodeException`: `DotProductf` does not support compilation | the third component, `cos(p) z + sin(p) (a y - b x) / abs([a, b, c])` | +| the same, `.Compile` | throws `UncompilableNodeException`: vectors over `Int64` and `Double` | the same; `-3.9818867534572675` at `(0.3, 1, 1.7, 2.4, 3.1, 3.8, 4.5)` | +| `"dot(x * [1, 2], [3, 4])".Compile("x")` | throws `UncompilableNodeException` | `11 x` | +| `"dot(x * [1, 2], [3, 4])".Compile("x")` at `x = 0.5` | `0` | `5.5` | +| `"det(x * [[1, 2], [3, 4]])".Compile("x")` | throws `UncompilableNodeException` | `-2 x ^ 2` | +| `"det(x * [[1, 2], [3, 4]])".Compile("x")` at `x = 0.5` | `0` | `-0.5` | +| `"[1, 0]T * transpose(x * [[1, 2], [3, 4]]) * [0, 1]"`, either compiler, at `x = 0.3` | `0` | `3 x`: `0.8999999999999999` | +| `"[1, 0]T * transpose(A) * [0, 1]"` over a number `A`, either compiler | `0` | throws `UncompilableNodeException`: the transpose is taken of a number | +| `"[0, 0, 1]T * cross(x * [1, 0, 0], [0, y, 0])"`, either compiler | throws `UncompilableNodeException` | `x y` | +| `"det(x * A)".Compile("x", "A")` at `x = 0.5`, `A = [[1, 2], [3, 4]]` | `0` | `-0.5` | +| `"trace(A / x)".Compile("x", "A")` at `x = 2`, the same `A` | `2` | `2.5` | +| `"x * A".Compile("x", "A")` at `x = 0.5`, the same `A` | throws `UncompilableNodeException`: a matrix over `Int64` | `[[0.5, 1], [1.5, 2]]` | +| `"dot(z * a, [1, 2])".Compile("z", "a")` at `z = i`, `a = [1, 2]` | throws `UncompilableNodeException`: no coercion from `Complex` to `Double` | `5i` | +| `"dot(a, b)".Compile("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 | + --- ## 2.9.0 — since 2.8.0 @@ -999,9 +1033,11 @@ In the other order each value computed at the defaults came back inside the scop **Not silent: what was refused now parses.** `dot(a, b)` and `cross(a, b)` threw `InvalidArgumentParseException` where an operand was not a vector written out. Now they are the nodes `DotProductf` and `CrossProductf`. Each is -computed once both operands are vectors: when they are substituted, by `Simplify`, `Evaled`, or a compiled delegate -taking `double[]`, `double[,]` or `Complex[]`. Of vectors written out each is still computed as it is parsed, and prints -as before. Vectors of different lengths, or a `cross` of vectors without three components, leave the node as it is. +computed once both operands are vectors, by `Simplify`, `Evaled`, or a compiled delegate taking `double[]`, `double[,]` +or `Complex[]`. Substituting vectors for the names puts them in and computes nothing, as in every node: +`dot([0, 0, 1], v)` with `v = [x, y, z]` substituted is `dot([0, 0, 1], [x, y, z])` until it is simplified or +evaluated. Of vectors written out each is still computed as it is parsed, and prints as before. Vectors of different +lengths, or a `cross` of vectors without three components, leave the node as it is. A number, or a written vector that cannot fit, is refused as before. The operands of `cross` are kept in their order, and so is a product with a `cross` in it. A name beside a written vector, as in `dot(x * [1, 2], [3, 4])`, may stand for a matrix, so the operand is no longer multiplied into the components as a number diff --git a/Sources/.editorconfig b/Sources/.editorconfig index 8e3112de7..238e8bc25 100644 --- a/Sources/.editorconfig +++ b/Sources/.editorconfig @@ -1216,3 +1216,9 @@ file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed [Tests/UnitTests/Convenience/InverseHyperbolicCosinePrincipalValueTest.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/Compilation/MatrixOperationsOverNumbers.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/Common/MatrixOperationOverNumbersCompilationTest.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 diff --git a/Sources/AngouriMath/Docs/Usage/Syntax.md b/Sources/AngouriMath/Docs/Usage/Syntax.md index 7086787d3..293bde5e0 100644 --- a/Sources/AngouriMath/Docs/Usage/Syntax.md +++ b/Sources/AngouriMath/Docs/Usage/Syntax.md @@ -269,7 +269,10 @@ numbers and it is `x ^ 2 - 2` `dot(a, b)` and `cross(a, b)` of a name are nodes too, carried out once both operands are vectors: `dot(a, b)` with `a` and `b` substituted by `[1, 2, 3]` and `[4, 5, 6]` simplifies to `32`, and `cross(W, r)` with `[0, 0, w]` and `[x, y, z]` to `[-w * y, w * x, 0]`. A compiled delegate takes -the vectors as `double[]` or `double[,]`, and `cross` returns a column. `cross` is not commutative, +the vectors as `double[]` or `double[,]`, and `cross` returns a column. A name compiled as a number is +one, so these and the matrix nodes above are carried out on it when compiling: over a number `x`, +`dot(x * [1, 2], [3, 4])` compiles to `11 x` and `det(x * [[1, 2], [3, 4]])` to `-2 x ^ 2`, the same +in `Compile(params Variable[])`, whose variables are all numbers. `cross` is not commutative, and its operands are kept in their order, as is a product with a `cross` in it: `cross(a, b) + cross(b, a)` is left as it is. Vectors of different lengths, or a `cross` of vectors that do not have three components, have no value, and the node is left as it is; where the vector is written out, as in diff --git a/Sources/AngouriMath/Functions/Compilation/IntoFE/Compiler.cs b/Sources/AngouriMath/Functions/Compilation/IntoFE/Compiler.cs index e10296d57..e1665da58 100644 --- a/Sources/AngouriMath/Functions/Compilation/IntoFE/Compiler.cs +++ b/Sources/AngouriMath/Functions/Compilation/IntoFE/Compiler.cs @@ -1090,6 +1090,12 @@ internal static FastExpression Compile(Entity func, IEnumerable variab varNamespace[varName] = id++; foreach (var constant in Variable.NamedConstants.Values) func = func.Substitute(constant, constant.Value); + // Every variable here is a number, so a scalar product, a determinant and the rest of a name beside a + // written matrix are carried out, and one still left cannot be a number and is refused. Left as nodes, + // they were refused for want of a compiled form, or read as numbers by the simplification below. + // https://github.com/asc-community/AngouriMath/issues/105 + func = Compilation.MatrixOperationsOverNumbers.Rewritten(func, varNamespace.ContainsKey); + Compilation.MatrixOperationsOverNumbers.Check(func, varNamespace.ContainsKey, anyLeft: true); // An expression built out of matrices often has a number for its value -- [1, 0]T * [[a, b], [c, d]] * [0, 1] // is b -- and the LINQ compiler simplifies such an expression first, for that reason. This one did not, and // refused it. https://github.com/asc-community/AngouriMath/issues/425 diff --git a/Sources/AngouriMath/Functions/Compilation/IntoLinq/IntoLinqCompiler.cs b/Sources/AngouriMath/Functions/Compilation/IntoLinq/IntoLinqCompiler.cs index 920fa8cf3..97d961068 100644 --- a/Sources/AngouriMath/Functions/Compilation/IntoLinq/IntoLinqCompiler.cs +++ b/Sources/AngouriMath/Functions/Compilation/IntoLinq/IntoLinqCompiler.cs @@ -30,6 +30,12 @@ internal static TDelegate Compile( // before compiling, so those failed along with the ones that genuinely cannot // be compiled (https://github.com/asc-community/AngouriMath/issues/425). // Only expressions that mention a matrix pay for this. + // A scalar product, a determinant and the rest of a name compiled as a number beside a written matrix are + // carried out first, as simplification will not, and one taken of a number is refused before simplification + // reads it as a number. https://github.com/asc-community/AngouriMath/issues/105 + bool IsNumberArgument(Variable variable) => typesAndNames.Any(c => c.variable == variable && !TensorCompilation.IsMatrixType(c.type)); + expr = MatrixOperationsOverNumbers.Rewritten(expr, IsNumberArgument); + MatrixOperationsOverNumbers.Check(expr, IsNumberArgument, anyLeft: false); if (expr.Nodes.Any(node => node is Entity.Matrix)) expr = TensorCompilation.SimplifiedAroundMatrixArguments(expr, IsMatrixArgument); expr = CompiledMembership.Rewritten(expr); diff --git a/Sources/AngouriMath/Functions/Compilation/IntoLinq/TensorCompilation.Elementwise.cs b/Sources/AngouriMath/Functions/Compilation/IntoLinq/TensorCompilation.Elementwise.cs index fb6390a37..3e4f6dd39 100644 --- a/Sources/AngouriMath/Functions/Compilation/IntoLinq/TensorCompilation.Elementwise.cs +++ b/Sources/AngouriMath/Functions/Compilation/IntoLinq/TensorCompilation.Elementwise.cs @@ -320,6 +320,19 @@ internal static (Expression Left, Expression Right) Widened(Expression left, Exp return (left, right); } + /// + /// A matrix beside a number of a wider type, widened to that type, as widens the narrower of + /// two matrices. The number was converted to the entries' type instead, which truncated it: over a double + /// x and a matrix argument A over long, det(x * A) was 0 at x = 0.5, and a complex + /// number beside a matrix over double was refused. Unchanged where the number is not wider than the entries. + /// https://github.com/asc-community/AngouriMath/issues/105 + /// + internal static Expression WidenedBeside(Expression tensor, Type number, Func convert) + { + var element = ElementOf(tensor.Type); + return element != number && mapKits.ContainsKey((element, number)) ? Widen(tensor, number, convert) : tensor; + } + private static Expression Widen(Expression tensor, Type to, Func convert) { var element = ElementOf(tensor.Type); diff --git a/Sources/AngouriMath/Functions/Compilation/IntoLinq/TensorCompilation.cs b/Sources/AngouriMath/Functions/Compilation/IntoLinq/TensorCompilation.cs index 596ab635d..54e579b65 100644 --- a/Sources/AngouriMath/Functions/Compilation/IntoLinq/TensorCompilation.cs +++ b/Sources/AngouriMath/Functions/Compilation/IntoLinq/TensorCompilation.cs @@ -765,10 +765,13 @@ public static int WholeIndex(Complex index) if (!kitsByTensor.ContainsKey(operand.Type)) throw new UncompilableNodeException( $"`{node.Stringize()}` is taken of vectors, and an operand compiles to {operand.Type.Name}: compile it with a vector or a matrix type, such as double[] or double[,], for the operands"); - if (operands[0].Type != operands[1].Type) - throw new UncompilableNodeException($"Two vectors over different element types, {ElementOf(operands[0].Type)} and {ElementOf(operands[1].Type)}, cannot be combined"); - var vectors = kitsByTensor[operands[0].Type]; - return Expression.Call(node is Entity.DotProductf ? vectors.Dot : vectors.Cross, operands[0], operands[1]); + // The narrower of two vectors widened to the other, as a sum of two matrices is: a written vector of whole + // numbers beside one over double was refused. https://github.com/asc-community/AngouriMath/issues/105 + var (left, right) = Widened(operands[0], operands[1], convert); + if (left.Type != right.Type) + throw new UncompilableNodeException($"Two vectors over different element types, {ElementOf(left.Type)} and {ElementOf(right.Type)}, cannot be combined"); + var vectors = kitsByTensor[left.Type]; + return Expression.Call(node is Entity.DotProductf ? vectors.Dot : vectors.Cross, left, right); } if (node is not (Entity.Transposef or Entity.Determinantf or Entity.Tracef or Entity.MatrixEntryf)) return null; @@ -826,6 +829,8 @@ internal static Expression Build(Entity.Matrix matrix, IReadOnlyList { if (node is Entity.Powf) return Expression.Call(leftKit!.Power, left, Exponent(right, convert)); + left = WidenedBeside(left, right.Type, convert); + leftKit = kitsByTensor[left.Type]; var scalar = convert(right, ElementOf(left.Type)); return node switch { @@ -836,6 +841,8 @@ internal static Expression Build(Entity.Matrix matrix, IReadOnlyList _ => null, }; } + right = WidenedBeside(right, left.Type, convert); + rightKit = kitsByTensor[right.Type]; var value = convert(left, ElementOf(right.Type)); return node switch { diff --git a/Sources/AngouriMath/Functions/Compilation/MatrixOperationsOverNumbers.cs b/Sources/AngouriMath/Functions/Compilation/MatrixOperationsOverNumbers.cs new file mode 100644 index 000000000..631380284 --- /dev/null +++ b/Sources/AngouriMath/Functions/Compilation/MatrixOperationsOverNumbers.cs @@ -0,0 +1,95 @@ +// +// 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; +using System.Linq; +using AngouriMath.Core.Exceptions; +using static AngouriMath.Entity; + +namespace AngouriMath.Core.Compilation +{ + /// + /// A determinant, a transpose, a trace, an entry, a scalar product or a vector product, carried out for the + /// compilers where every name in it is compiled as a number. Simplification leaves each of them as written where a + /// name stands beside a written matrix, since the name may stand for a matrix: dot([0, 0, 1], cos(p) * [x, y, z]) + /// is left as it is. A variable compiled as a number is one, so for the compiler the operand is the vector + /// [cos(p) * x, cos(p) * y, cos(p) * z], and the product is carried out on that. Left as written, the + /// FastExpression compiler had no form for the node and refused it, and simplification before compiling read a + /// transpose or a vector product beside a written matrix as a number: + /// [1, 0]T * transpose(x * [[1, 2], [3, 4]]) * [0, 1] compiled to 0, where it is 3 x. + /// https://github.com/asc-community/AngouriMath/issues/105 + /// https://github.com/asc-community/AngouriMath/issues/2147 + /// + internal static class MatrixOperationsOverNumbers + { + internal static bool IsMatrixOperation(Entity node) + => node is Determinantf or Transposef or Tracef or MatrixEntryf or DotProductf or CrossProductf; + + /// + /// with each matrix operation whose names are all numbers carried out, innermost + /// first, so that a vector product inside a scalar product is a vector by the time the scalar product is taken. + /// One that has no value even so -- vectors of different lengths, or an argument that is a number -- is left. + /// + /// The expression about to be compiled, its named constants already substituted. + /// Whether a variable is compiled as a number. + internal static Entity Rewritten(Entity expression, Func isNumber) + => expression.Nodes.Any(IsMatrixOperation) + ? expression.Replace(node => IsMatrixOperation(node) && node.Vars.All(isNumber) ? CarriedOut(node) : node) + : expression; + + private static Entity CarriedOut(Entity node) => node switch + { + Determinantf determinant => determinant.CarriedOut(isExact: true, namesAreNumbers: true), + Transposef transpose => transpose.CarriedOut(isExact: true, namesAreNumbers: true), + Tracef trace => trace.CarriedOut(isExact: true, namesAreNumbers: true), + MatrixEntryf entry => entry.CarriedOut(isExact: true, namesAreNumbers: true), + DotProductf dot => dot.CarriedOut(isExact: true, namesAreNumbers: true), + CrossProductf cross => cross.CarriedOut(isExact: true, namesAreNumbers: true), + _ => node, + }; + + /// + /// Refuses a matrix operation left by whose names are all numbers and whose argument has + /// no matrix in it: it is taken of a number, and has no value. Refused here, before simplification reads it as a + /// number beside a written matrix and multiplies it into the entries, which gave + /// [1, 0]T * transpose(A) * [0, 1] the value 0. With , every matrix operation + /// left is refused: a FastExpression has numbers for its variables and its value, and nothing left can become one. + /// + /// Such an operation is left. + internal static void Check(Entity expression, Func isNumber, bool anyLeft) + { + if (!expression.Nodes.Any(IsMatrixOperation)) + return; + foreach (var node in expression.Nodes) + if (IsMatrixOperation(node) && node.Vars.All(isNumber) && (anyLeft || TakenOfANumber(node))) + throw new UncompilableNodeException( + $"`{node.Stringize()}` is taken of {Operand(node)}, and " + + (TakenOfANumber(node) + ? (node is DotProductf or CrossProductf ? "an operand" : "its argument") + " is a number where its variables are compiled as numbers." + : "its operands do not have that shape, or an index is not a whole number known when compiling.") + + (anyLeft + ? " A FastExpression's variables and value are numbers: compile it with Compile<..., double[]>, Compile<..., double[,]> or their Complex forms to have vectors and matrices." + : " Compile it with a vector or a matrix type, such as double[] or double[,], for a name that stands for one.")); + } + + // The arguments a matrix is expected in: the first of an entry, and both operands of a product. + private static bool TakenOfANumber(Entity node) + => node is DotProductf or CrossProductf + ? node.DirectChildren.Any(NoMatrixIn) + : NoMatrixIn(node.DirectChildren[0]); + + private static bool NoMatrixIn(Entity argument) => !argument.Nodes.Any(n => n is Matrix); + + private static string Operand(Entity node) => node switch + { + DotProductf => "two vectors of one length", + CrossProductf => "two vectors of three components", + Determinantf or Tracef => "a square matrix", + _ => "a matrix", + }; + } +} diff --git a/Sources/AngouriMath/Functions/Evaluation/Evaluation.Omni/Evaluation.Omni.Classes.cs b/Sources/AngouriMath/Functions/Evaluation/Evaluation.Omni/Evaluation.Omni.Classes.cs index 5b3a8e61a..2b4a16e83 100644 --- a/Sources/AngouriMath/Functions/Evaluation/Evaluation.Omni/Evaluation.Omni.Classes.cs +++ b/Sources/AngouriMath/Functions/Evaluation/Evaluation.Omni/Evaluation.Omni.Classes.cs @@ -582,12 +582,17 @@ protected override Entity InnerSimplify(bool isExact) /// The value at a matrix, or null where the matrix has none, as a matrix that is not square has no determinant. /// The value at anything else, a rewrite such as det(transpose(A)) = det(A), or null. /// The node, over the simplified argument. + /// + /// Whether every name in is known to be a number, as a compiler knows of a variable + /// it compiles as one. The operation is then carried out on the matrix simplification makes of the argument. + /// private static Entity OnMatrixArgument(Entity argument, bool isExact, Func ofMatrix, - Func ofOther, Func unevaluated) + Func ofOther, Func unevaluated, bool namesAreNumbers = false) { // A name beside a written matrix may stand for a matrix, and simplification reads it as a number: // A [[2, 0], [0, 3]] simplifies to [[2 A, 0], [0, 3 A]], whose determinant 6 A^2 is not det(A) det(...). - var readsANameAsANumber = argument is not Matrix && HasANameOutsideAWrittenMatrix(argument); + // Where every name is known to be a number, that reading is the right one. + var readsANameAsANumber = !namesAreNumbers && argument is not Matrix && HasANameOutsideAWrittenMatrix(argument); Entity Over(Entity simplified) => simplified switch { Matrix matrix => (readsANameAsANumber ? null : ofMatrix(matrix)) ?? unevaluated(readsANameAsANumber ? argument : matrix), @@ -610,11 +615,12 @@ private static Entity OnMatrixArgument(Entity argument, bool isExact, FuncWhether to keep the answer exact, as for simplification against evaluation. /// The value at two matrices, or null where they have none, as vectors of different lengths have no scalar product. /// The node, over the simplified operands. + /// Whether every name in either operand is known to be a number, as for . private static Entity OnTwoMatrixArguments(Entity left, Entity right, bool isExact, - Func ofMatrices, Func unevaluated) + Func ofMatrices, Func unevaluated, bool namesAreNumbers = false) { - var leftReadsANameAsANumber = left is not Matrix && HasANameOutsideAWrittenMatrix(left); - var rightReadsANameAsANumber = right is not Matrix && HasANameOutsideAWrittenMatrix(right); + var leftReadsANameAsANumber = !namesAreNumbers && left is not Matrix && HasANameOutsideAWrittenMatrix(left); + var rightReadsANameAsANumber = !namesAreNumbers && right is not Matrix && HasANameOutsideAWrittenMatrix(right); Entity Simplified(Entity operand) => operand is Matrix written ? written.Elementwise(e => e.InnerSimplified(isExact)) : operand.InnerSimplified(isExact); Entity Over(Entity l, Entity r) => (l, r) switch @@ -654,35 +660,49 @@ partial record Determinantf // Whether there is a determinant depends on the shape alone, which no condition on the entries can say. private protected override Entity IntrinsicCondition => Boolean.True; /// - protected override Entity InnerSimplify(bool isExact) + protected override Entity InnerSimplify(bool isExact) => CarriedOut(isExact, namesAreNumbers: false); + + /// + /// What gives, or, with , the operation carried out + /// on the matrix simplification makes of an argument whose every name is known to be a number. The compilers + /// ask for the second for the variables they compile as numbers. The same holds of the transpose, the trace, an + /// entry, and the scalar and the vector product. + /// + internal Entity CarriedOut(bool isExact, bool namesAreNumbers) => OnMatrixArgument(Argument, isExact, matrix => matrix.IsSquare ? matrix.Determinant?.InnerSimplified(isExact) : null, // det(A^T) = det(A), the one being defined exactly where the other is. other => other is Transposef(var inner) ? new Determinantf(inner).InnerSimplified(isExact) : null, - New); + New, namesAreNumbers); } partial record Transposef { private protected override Entity IntrinsicCondition => Boolean.True; /// - protected override Entity InnerSimplify(bool isExact) + protected override Entity InnerSimplify(bool isExact) => CarriedOut(isExact, namesAreNumbers: false); + + /// + internal Entity CarriedOut(bool isExact, bool namesAreNumbers) => OnMatrixArgument(Argument, isExact, matrix => matrix.T.InnerSimplified(isExact), other => other is Transposef(var inner) ? inner : null, - New); + New, namesAreNumbers); } partial record Tracef { private protected override Entity IntrinsicCondition => Boolean.True; /// - protected override Entity InnerSimplify(bool isExact) + protected override Entity InnerSimplify(bool isExact) => CarriedOut(isExact, namesAreNumbers: false); + + /// + internal Entity CarriedOut(bool isExact, bool namesAreNumbers) => OnMatrixArgument(Argument, isExact, matrix => matrix.IsSquare ? matrix.Trace.InnerSimplified(isExact) : null, // The transpose has the same diagonal. other => other is Transposef(var inner) ? new Tracef(inner).InnerSimplified(isExact) : null, - New); + New, namesAreNumbers); } partial record MatrixEntryf @@ -696,7 +716,10 @@ partial record MatrixEntryf : null; /// - protected override Entity InnerSimplify(bool isExact) + protected override Entity InnerSimplify(bool isExact) => CarriedOut(isExact, namesAreNumbers: false); + + /// + internal Entity CarriedOut(bool isExact, bool namesAreNumbers) { var row = Row.InnerSimplified(isExact); var column = Column.InnerSimplified(isExact); @@ -706,7 +729,7 @@ protected override Entity InnerSimplify(bool isExact) : null, // The (i, j) entry of the transpose is the (j, i) entry of the matrix. other => other is Transposef(var inner) ? new MatrixEntryf(inner, column, row).InnerSimplified(isExact) : null, - argument => New(argument, row, column)); + argument => New(argument, row, column), namesAreNumbers); } } @@ -715,16 +738,22 @@ partial record DotProductf // Whether there is a scalar product depends on the shapes alone, which no condition on the entries can say. private protected override Entity IntrinsicCondition => Boolean.True; /// - protected override Entity InnerSimplify(bool isExact) - => OnTwoMatrixArguments(Left, Right, isExact, (a, b) => Of(a, b)?.InnerSimplified(isExact), New); + protected override Entity InnerSimplify(bool isExact) => CarriedOut(isExact, namesAreNumbers: false); + + /// + internal Entity CarriedOut(bool isExact, bool namesAreNumbers) + => OnTwoMatrixArguments(Left, Right, isExact, (a, b) => Of(a, b)?.InnerSimplified(isExact), New, namesAreNumbers); } partial record CrossProductf { private protected override Entity IntrinsicCondition => Boolean.True; /// - protected override Entity InnerSimplify(bool isExact) - => OnTwoMatrixArguments(Left, Right, isExact, (a, b) => Of(a, b)?.InnerSimplified(isExact), New); + protected override Entity InnerSimplify(bool isExact) => CarriedOut(isExact, namesAreNumbers: false); + + /// + internal Entity CarriedOut(bool isExact, bool namesAreNumbers) + => OnTwoMatrixArguments(Left, Right, isExact, (a, b) => Of(a, b)?.InnerSimplified(isExact), New, namesAreNumbers); } partial record Matrix diff --git a/Sources/Tests/UnitTests/Common/DotAndCrossNodesTest.cs b/Sources/Tests/UnitTests/Common/DotAndCrossNodesTest.cs index accd7a271..b8c2fa0e9 100644 --- a/Sources/Tests/UnitTests/Common/DotAndCrossNodesTest.cs +++ b/Sources/Tests/UnitTests/Common/DotAndCrossNodesTest.cs @@ -17,8 +17,9 @@ namespace AngouriMath.Tests.Common { /// /// dot(a, b) and cross(a, b) of a name that stands for a vector: nodes, computed once both operands are - /// vectors, by substitution, simplification, evaluation or a compiled delegate. Every value is checked against one - /// computed here from the components, at real, negative and non-real vectors. + /// vectors, by simplification, evaluation or a compiled delegate. Substitution puts the vectors in and computes + /// nothing, as in every other node. Every value is checked against one computed here from the components, at real, + /// negative and non-real vectors. /// #105 /// [Trait("Area", "Common")] @@ -118,6 +119,21 @@ public void TheScalarProductOfSubstitutedVectorsIsTheirScalarProduct() } } + // Substitution computes nothing, in these nodes as in a determinant or a sine: the vectors put in are multiplied + // out by Simplify, Evaled or a compiled delegate. + [Fact] + public void SubstitutionPutsTheVectorsInAndLeavesTheProductToSimplification() + { + var dot = "dot([0, 0, 1], v)".ToEntity().Substitute("v", "[x, y, z]"); + Assert.Equal(new Entity.DotProductf("[0, 0, 1]", "[x, y, z]"), dot); + Assert.Equal("z".ToEntity(), dot.Simplify()); + Assert.Equal("z".ToEntity(), dot.InnerSimplified); + var cross = "cross(W, r)".ToEntity().Substitute("W", "[0, 0, w]").Substitute("r", "[x, y, z]"); + Assert.Equal(new Entity.CrossProductf("[0, 0, w]", "[x, y, z]"), cross); + Assert.Equal("[-w * y, w * x, 0]".ToEntity(), cross.Simplify()); + Assert.Equal(new Entity.Determinantf("[[1, 2], [3, 4]]"), "det(A)".ToEntity().Substitute("A", "[[1, 2], [3, 4]]")); + } + [Fact] public void TheVectorProductOfSubstitutedVectorsIsTheirVectorProduct() { @@ -283,6 +299,9 @@ public void TheProductsCompile() // Of a matrix argument and a vector written out, and of a name beside one, read as a number by the delegate. Assert.Equal(10, "dot(M * a, a)".ToEntity().Compile("M", "a")(new double[,] { { 1, 2 }, { 3, 4 } }, new double[] { 1, 1 }), 12); Assert.Equal(22, "dot(x * [1, 2], [3, 4])".ToEntity().Compile("x")(2), 12); + // And at a number that is not whole, which the written vector's whole numbers truncated to 0. + Assert.Equal(5.5, "dot(x * [1, 2], [3, 4])".ToEntity().Compile("x")(0.5), 12); + Assert.Equal(new Complex(5.5, 0), "dot(x * [1, 2], [3, 4])".ToEntity().Compile("x").Call(0.5)); } [Fact] diff --git a/Sources/Tests/UnitTests/Common/MatrixOperationOverNumbersCompilationTest.cs b/Sources/Tests/UnitTests/Common/MatrixOperationOverNumbersCompilationTest.cs new file mode 100644 index 000000000..1958a4c62 --- /dev/null +++ b/Sources/Tests/UnitTests/Common/MatrixOperationOverNumbersCompilationTest.cs @@ -0,0 +1,197 @@ +// +// 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; +using System.Linq; +using System.Numerics; +using AngouriMath; +using AngouriMath.Core.Exceptions; +using AngouriMath.Extensions; +using Xunit; +using static AngouriMath.Entity; + +namespace AngouriMath.Tests.Common +{ + /// + /// A scalar or a vector product, a determinant, a transpose, a trace or an entry of a name beside a written matrix, + /// compiled with that name a number. Simplification leaves each as written, since the name may stand for a matrix; + /// a compiled variable has a type, and one compiled as a number is one. The FastExpression compiler had no form for + /// any of them and refused them, the LINQ compiler converted the number to the whole numbers of the written matrix + /// and truncated it, and both read a transpose or a vector product beside a written matrix as a number. Every value + /// is checked against the definition written out here, at real, negative and non-real points. + /// #105 + /// + [Trait("Area", "Common")] + public sealed class MatrixOperationOverNumbersCompilationTest + { + private static void Near(Complex expected, Complex actual) + => Assert.True(Complex.Abs(expected - actual) <= 1e-9 * Math.Max(1, Complex.Abs(expected)), $"expected {expected}, got {actual}"); + + private static Complex[] Cross(Complex[] u, Complex[] v) + => new[] { u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0] }; + + private static Complex Dot(Complex[] u, Complex[] v) => u.Zip(v, (a, b) => a * b).Aggregate(Complex.Zero, (s, t) => s + t); + + // The inclination reference's I_x and I_y take the third component of a vector built from vectors: a rotation of + // v about g through p, cos(p) v + sin(p) / |g| (g x v). Its third component, by the definition: cos(p) z + + // sin(p) / |g| (a y - b x), |g| being the norm sqrt(|a|^2 + |b|^2 + |c|^2) that abs takes of a vector. + private const string Rotated = "cos(p) * [x, y, z] + sin(p) / abs([a, b, c]) * cross([a, b, c], [x, y, z])"; + + private static Complex ThirdComponent(Complex a, Complex b, Complex c, Complex p, Complex x, Complex y, Complex z) + => Complex.Cos(p) * z + Complex.Sin(p) / Math.Sqrt(Complex.Abs(a) * Complex.Abs(a) + Complex.Abs(b) * Complex.Abs(b) + Complex.Abs(c) * Complex.Abs(c)) * (a * y - b * x); + + private static readonly Complex[][] Points = + { + new Complex[] { 0.3, 1, 1.7, 2.4, 3.1, 3.8, 4.5 }, + new Complex[] { -1.5, 0.25, -4, -0.7, 2, -3, 0.5 }, + new Complex[] { new(1, 2), -3, new(0, -1), new(0.5, 0.25), new(2.5, 0.5), new(-1, 1), 2 }, + }; + + [Theory] + [InlineData("dot([0, 0, 1], " + Rotated + ")")] + [InlineData("dot(" + Rotated + ", [0, 0, 1])")] + [InlineData("[0, 0, 1]T * (" + Rotated + ")")] + public void TheThirdComponentOfAVectorExpressionCompilesToAFastExpression(string expression) + { + var f = expression.ToEntity().Compile("a", "b", "c", "p", "x", "y", "z"); + foreach (var at in Points) + Near(ThirdComponent(at[0], at[1], at[2], at[3], at[4], at[5], at[6]), f.Call(at)); + } + + [Fact] + public void TheThirdComponentOfAVectorExpressionCompilesOverTheReals() + { + var f = ("dot([0, 0, 1], " + Rotated + ")").ToEntity().Compile("a", "b", "c", "p", "x", "y", "z"); + foreach (var at in Points.Take(2)) + { + var r = at.Select(c => c.Real).ToArray(); + Near(ThirdComponent(at[0], at[1], at[2], at[3], at[4], at[5], at[6]), f(r[0], r[1], r[2], r[3], r[4], r[5], r[6])); + } + } + + // Of a vector product of vectors built from names, compiled where the whole is a number. + [Theory] + [InlineData("dot([1, 2, 3], cross(x * [1, 0, -1] + [0, y, 0], [z, 1, x]))")] + [InlineData("[1, 2, 3]T * cross(x * [1, 0, -1] + [0, y, 0], [z, 1, x])")] + public void AVectorProductOfAVectorExpressionCompiles(string expression) + { + var f = expression.ToEntity().Compile("x", "y", "z"); + var g = expression.ToEntity().Compile("x", "y", "z"); + foreach (var (x, y, z) in new (Complex, Complex, Complex)[] { (0.5, 2, -1), (-1.25, 0.5, 3), (new(1, 1), new(0, -2), 0.5) }) + { + var expected = Dot(new Complex[] { 1, 2, 3 }, Cross(new[] { x, y, -x }, new[] { z, 1, x })); + Near(expected, f.Call(x, y, z)); + Near(expected, g(x, y, z)); + } + } + + // det(x M) = x^2 det(M), trace(x M) = x trace(M), the (2, 1) entry of x M is 3 x, and the (1, 2) entry of its + // transpose too. The transpose beside written matrices compiled to 0 in both compilers, read as a number. + [Theory] + [InlineData("det(x * [[1, 2], [3, 4]])", -2, 2)] + [InlineData("det(transpose(x * [[1, 2], [3, 4]]))", -2, 2)] + [InlineData("trace(x * [[1, 2], [3, 4]])", 5, 1)] + [InlineData("(x * [[1, 2], [3, 4]])[2, 1]", 3, 1)] + [InlineData("[1, 0]T * transpose(x * [[1, 2], [3, 4]]) * [0, 1]", 3, 1)] + [InlineData("dot(x * [1, 2], [3, 4])", 11, 1)] + [InlineData("dot([0, 0, 1], x * [1, 2, 3])", 3, 1)] + public void AMatrixOperationOfANameBesideAWrittenMatrixCompiles(string expression, double coefficient, int power) + { + var e = expression.ToEntity(); + var fast = e.Compile("x"); + var overReals = e.Compile("x"); + var overComplex = e.Compile("x"); + foreach (var x in new Complex[] { 0.5, -1.5, 2, new(0.25, -1) }) + { + var expected = coefficient * Complex.Pow(x, power); + Near(expected, fast.Call(x)); + Near(expected, overComplex(x)); + if (x.Imaginary == 0) + Near(expected, overReals(x.Real)); + } + } + + // A number beside a matrix of whole numbers, as an argument, widens it; it was converted to a whole number, and + // 0.5 times the matrix was the zero matrix. + [Fact] + public void ANumberBesideAMatrixOfWholeNumbersIsNotTruncated() + { + var a = new long[,] { { 1, 2 }, { 3, 4 } }; + Assert.Equal(-0.5, "det(x * A)".ToEntity().Compile("x", "A")(0.5, a), 12); + Assert.Equal(1.5, "(x * A)[2, 1]".ToEntity().Compile("x", "A")(0.5, a), 12); + Assert.Equal(2.5, "trace(A / x)".ToEntity().Compile("x", "A")(2, a), 12); + Assert.Equal(new[,] { { 0.5, 1 }, { 1.5, 2 } }, "x * A".ToEntity().Compile("x", "A")(0.5, a)); + // A complex number beside a matrix over double, which was refused. + Near(new Complex(0, 5), "dot(z * a, [1, 2])".ToEntity().Compile("z", "a")(Complex.ImaginaryOne, new double[] { 1, 2 })); + } + + // Two vectors over different element types are widened to the wider, as two matrices added are. + [Fact] + public void TwoVectorsOverDifferentTypesAreWidened() + { + var u = new double[] { 1, 2, 3 }; + var v = new Complex[] { Complex.ImaginaryOne, 1, new(2, -1) }; + var dot = "dot(a, b)".ToEntity().Compile("a", "b"); + Near(Dot(u.Select(c => (Complex)c).ToArray(), v), dot(u, v)); + var cross = "cross(a, b)".ToEntity().Compile("a", "b"); + var expected = Cross(u.Select(c => (Complex)c).ToArray(), v); + var actual = cross(u, v); + for (var i = 0; i < 3; i++) + Near(expected[i], actual[i]); + var crossOfWholeNumbers = "cross([1, 0, 0], x * [0, 1, 0])".ToEntity().Compile("x"); + Assert.Equal(new[] { 0, 0, 0.5 }, crossOfWholeNumbers(0.5)); + } + + // Of a number there is no product, determinant or transpose: refused, where the transpose beside written + // matrices was read as a number and compiled to 0. + [Theory] + [InlineData("dot(a, b)")] + [InlineData("cross(a, b)")] + [InlineData("det(a)")] + [InlineData("trace(a) + b")] + [InlineData("[1, 0]T * transpose(a) * [0, 1]")] + [InlineData("[0, 0, 1]T * cross(a, b)")] + public void AMatrixOperationOfANumberIsRefused(string expression) + { + var e = expression.ToEntity(); + var vars = e.Vars.ToArray(); + Assert.Contains("is a number where its variables are compiled as numbers", Assert.Throws(() => e.Compile(vars)).Message); + Assert.Throws(() => IntoLinq(e, vars.Length)); + } + + private static Delegate IntoLinq(Entity e, int count) => count switch + { + 1 => e.Compile("a"), + _ => e.Compile("a", "b"), + }; + + // A FastExpression computes numbers, so what is not carried out when compiling is refused, saying where the + // matrices can be had, rather than asking for a bug report. + [Fact] + public void WhatAFastExpressionCannotCarryOutIsRefusedAndSaysWhy() + { + var ofDifferentLengths = Assert.Throws(() => MathS.Matrices.DotProduct("[x, 2]", "[1, 2, 3]").Compile("x")); + Assert.Contains("double[]", ofDifferentLengths.Message); + Assert.DoesNotContain("report", ofDifferentLengths.Message); + // An index known only when called: the LINQ compiler indexes the matrix then. + var atAnIndex = "([[1, 2], [3, 4]] * x)[k, 1]".ToEntity(); + Assert.Contains("index", Assert.Throws(() => atAnIndex.Compile("k", "x")).Message); + Assert.Equal(1.5, atAnIndex.Compile("k", "x")(2, 0.5), 12); + } + + // A name compiled as a matrix is not read as a number: the operation over it is compiled on the matrix. + [Fact] + public void ANameCompiledAsAMatrixIsNotReadAsANumber() + { + var a = new double[,] { { 1, 2 }, { 3, 4 } }; + Assert.Equal(-0.5, "det(x * A)".ToEntity().Compile("x", "A")(0.5, a), 12); + Assert.Equal(3, "[1, 0]T * transpose(A) * [0, 1]".ToEntity().Compile("A")(a), 12); + // x a = [1.5, 1.5], whose scalar product with [1, 2] is 4.5, and det(A) = 4. + Assert.Equal(8.5, "dot(x * a, [1, 2]) + det(A)".ToEntity().Compile("x", "a", "A")(0.5, new double[] { 3, 3 }, new double[,] { { 2, 0 }, { 0, 2 } }), 12); + } + } +}