From 23a09d309e4021da52e73befe433292dcd04267d Mon Sep 17 00:00:00 2001 From: Rafael Vuijk Date: Sun, 15 Nov 2026 01:40:03 +0000 Subject: [PATCH] Make dot and cross nodes that apply to a name for a vector dot(a, b) and cross(a, b) of a name threw InvalidArgumentParseException at parse time, so a vector could not be substituted later. They are now the nodes DotProductf and CrossProductf, computed once both operands are vectors, by substitution, InnerSimplified, Evaled and a compiled delegate over double[], double[,] or Complex[] (dot to a scalar, cross to a column). Vectors written out are still computed when parsed and print as before. Errors follow det: a number, a statement, a set, a written matrix that is not a vector, or a written vector that cannot fit (cross(a, [1, 2])) is refused at parse time; operands that turn out not to fit after substitution leave the node unevaluated; a compiled delegate throws InvalidMatrixOperationException at the call, or at Compile where the shapes are written out. cross is not commutative: a product with an unevaluated cross in it is kept in its order, as one with a transpose is, and nothing reorders its operands. A name beside a written vector, dot(x * [1, 2], [3, 4]), is left as a node, as det leaves det(x * [[1, 2], [3, 4]]); it was multiplied in as a number. Recorded in BREAKING-CHANGES.md. MatrixFunctionsInAnExpressionTest's dot(A, [1, 2]) row moved from refused to parsed, since that is the change. Part of #105 Co-Authored-By: Claude Opus 5.5 --- BREAKING-CHANGES.md | 28 ++ Sources/.editorconfig | 3 + Sources/AngouriMath/Convenience/MathS.cs | 38 +++ .../AngouriMath/Core/Antlr/ParsingHelpers.cs | 64 ++-- Sources/AngouriMath/Core/Domains.Classes.cs | 18 ++ .../Omni/Entity.MatrixOperations.Classes.cs | 69 +++- .../Serialization/Entity.Serialization.cs | 2 + .../Transformations/Matching/MatchPattern.cs | 2 + .../Docs/Contributing/WritingARule.md | 2 +- Sources/AngouriMath/Docs/Usage/Syntax.md | 10 + .../Compilation/IntoLinq/TensorCompilation.cs | 87 ++++- .../Functions/Continuous/Differentiation.cs | 26 ++ .../EquationSolver/InvertNode.Classes.cs | 12 + .../Evaluation.Omni.Classes.cs | 55 +++- .../Output/Latex/Latex.Omni.Classes.cs | 17 + .../Output/ToString/ToString.Omni.Classes.cs | 17 + .../Output/ToSympy/ToSympy.Omni.Classes.cs | 12 + .../Simplification/Patterns/Patterns.cs | 10 +- .../Simplification/ProductsOfMatrices.cs | 25 +- .../Functions/Simplification/Simplificator.cs | 5 +- Sources/AngouriMath/Functions/Substitute.cs | 14 + .../Functions/TreeAnalyzer/Sort.Classes.cs | 12 + Sources/MCP/AngouriMath.Mcp/Resources.cs | 7 +- Sources/Tests/McpUnitTests/ParsingTest.cs | 2 +- .../UnitTests/Common/DotAndCrossNodesTest.cs | 305 ++++++++++++++++++ Sources/Tests/UnitTests/Common/PublicApi.txt | 44 +++ .../MatrixFunctionsInAnExpressionTest.cs | 7 +- .../Convenience/StringizeRoundTripTest.cs | 2 + .../Transformations/RuleAuthoringGuideTest.cs | 2 +- 29 files changed, 844 insertions(+), 53 deletions(-) create mode 100644 Sources/Tests/UnitTests/Common/DotAndCrossNodesTest.cs diff --git a/BREAKING-CHANGES.md b/BREAKING-CHANGES.md index ed80dd814..d3aa330ec 100644 --- a/BREAKING-CHANGES.md +++ b/BREAKING-CHANGES.md @@ -83,6 +83,34 @@ Euler's totient is `phi(n)`, and `φ(n)` and `ϕ(n)` are refused. Each name with | `"divergence(x)".ToEntity()` | `divergence * x` | throws `UnrecognizedFunctionParseException` | | `"gradient(x^2*y, [x, y])".ToEntity()` | throws `UnhandledParseException` | throws `UnrecognizedFunctionParseException` | +### `dot` and `cross` of a name for a vector are nodes + +**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. +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 +([#105](https://github.com/asc-community/AngouriMath/issues/105)). + +| Input | Was (2.7.0) | Now | +|---|---|---| +| `"dot(a, b)".ToEntity()` | throws `InvalidArgumentParseException` | `dot(a, b)`, a `DotProductf` | +| `"cross(W, r)".ToEntity()` | throws `InvalidArgumentParseException` | `cross(W, r)`, a `CrossProductf` | +| `"dot([1, 2, 3], b)".ToEntity()` | throws `InvalidArgumentParseException` | `dot([1, 2, 3], b)` | +| `"dot(a, b)"` with `a = [1, 2, 3]`, `b = [4, 5, 6]` substituted, `.Simplify()` | throws `InvalidArgumentParseException` | `32` | +| `"cross(W, r)"` with `W = [0, 0, w]`, `r = [x, y, z]` substituted, `.Simplify()` | throws `InvalidArgumentParseException` | `[-w * y, w * x, 0]` | +| `"dot(a, b)"` with `a = [1, 2, 3]`, `b = [4, 5]` substituted, `.Evaled` | throws `InvalidArgumentParseException` | `dot([1, 2, 3], [4, 5])`, left | +| `"dot(x * [1, 2], [3, 4])".ToEntity()` | `x * 3 + x * 2 * 4` | `dot(x * [1, 2], [3, 4])`: `x` may stand for a matrix | +| `"dot(5, a)".ToEntity()` | throws `InvalidArgumentParseException` | throws `InvalidArgumentParseException`, saying `dot` is taken of vectors | +| `"cross(a, [1, 2])".ToEntity()` | throws `InvalidArgumentParseException` | throws `InvalidArgumentParseException`, naming `[1, 2]` | +| `"dot([1, 2, 3], [4, 5, 6])".ToEntity()` | `1 * 4 + 2 * 5 + 3 * 6` | unchanged | +| `"cross([0, 0, w], [x, y, z])".ToEntity()` | `[0 * z - w * y, w * x - 0 * z, 0 * y - 0 * x]` | unchanged | + +`cross(a)` of one vector in the plane has no node, and still takes a vector written out. + --- ### A system row that is not a solution declines the system diff --git a/Sources/.editorconfig b/Sources/.editorconfig index 11b4496c9..7604ded7f 100644 --- a/Sources/.editorconfig +++ b/Sources/.editorconfig @@ -1096,3 +1096,6 @@ file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed [AngouriMath/Convenience/MathS.Equality.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/DotAndCrossNodesTest.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/Convenience/MathS.cs b/Sources/AngouriMath/Convenience/MathS.cs index f84a29bbe..ad2de932b 100644 --- a/Sources/AngouriMath/Convenience/MathS.cs +++ b/Sources/AngouriMath/Convenience/MathS.cs @@ -6050,6 +6050,44 @@ public static Matrix Matrix(int rows, int columns, params Entity[] values) => /// https://github.com/asc-community/AngouriMath/issues/2147 /// public static Entity Entry(Entity matrix, Entity row, Entity column) => new MatrixEntryf(matrix, row, column); + + /// + /// The scalar product dot(a, b) of two vectors of one length, as a node: the sum of the products of + /// their components, neither side conjugated. + /// + /// The first vector, written out or a name that stands for one. + /// The second vector, written out or a name that stands for one. + /// The node, computed once both operands are vectors + /// + /// Vectors of different lengths have no scalar product, and the node is left as it is. + /// https://github.com/asc-community/AngouriMath/issues/105 + /// + /// + /// + /// var dot = MathS.Matrices.DotProduct("a", "b"); + /// Console.WriteLine(dot); + /// Console.WriteLine(dot.Substitute("a", "[1, 2, 3]").Substitute("b", "[4, 5, 6]").Evaled); + /// + /// Prints + /// + /// dot(a, b) + /// 32 + /// + /// + public static Entity DotProduct(Entity left, Entity right) => new DotProductf(left, right); + + /// + /// The vector product cross(a, b) of two vectors in three dimensions, as a node. It is not + /// commutative, and its operands are kept in their order. + /// + /// The first vector, written out or a name that stands for one. + /// The second vector, written out or a name that stands for one. + /// The node, computed once both operands are vectors + /// + /// Anything but two vectors of three components has no vector product, and the node is left as it is. + /// https://github.com/asc-community/AngouriMath/issues/105 + /// + public static Entity CrossProduct(Entity left, Entity right) => new CrossProductf(left, right); } /// diff --git a/Sources/AngouriMath/Core/Antlr/ParsingHelpers.cs b/Sources/AngouriMath/Core/Antlr/ParsingHelpers.cs index ea23835e3..c6a709ede 100644 --- a/Sources/AngouriMath/Core/Antlr/ParsingHelpers.cs +++ b/Sources/AngouriMath/Core/Antlr/ParsingHelpers.cs @@ -31,9 +31,9 @@ internal static Matrix TryBuildingMatrix(List elements) return tb.ToMatrix() ?? throw new AngouriBugException("Should've been checked already"); } - // det, transpose, dot, cross and resultant are computed from what they are applied to where it - // is a matrix written out, or an expression that is one once its operations are carried out, - // as 2 [[1, 2], [3, 4]] is. https://github.com/asc-community/AngouriMath/issues/2147 + // cross of one vector and resultant are computed from what they are applied to where it is a + // matrix written out, or an expression that is one once its operations are carried out, as + // 2 [[1, 2], [3, 4]] is. https://github.com/asc-community/AngouriMath/issues/2147 private static Matrix MatrixArgument(string function, Entity argument, string example) => argument as Matrix ?? argument.InnerSimplified as Matrix ?? throw new InvalidArgumentParseException( @@ -42,18 +42,31 @@ private static Matrix MatrixArgument(string function, Entity argument, string ex // A matrix written out, or null where the argument may yet stand for one -- a name, or an // expression with a name in it beside a matrix, as A [[1, 2], [3, 4]] is, which simplifying - // would read as a number -- and det, transpose, trace and an entry are left as nodes over - // it. A number, a statement or a set is no matrix, and is refused as it was. - private static Matrix? MatrixOrUnknown(string function, Entity argument, string example) + // would read as a number -- and det, transpose, trace, an entry, dot and cross are left as + // nodes over it. A number, a statement or a set is no matrix, and is refused as it was. + private static Matrix? MatrixOrUnknown(string function, Entity argument, string example, string what = "a matrix") => (argument as Matrix ?? argument.InnerSimplified) switch { Matrix when argument is not Matrix && HasANameOutsideAWrittenMatrix(argument) => null, Matrix matrix => matrix, Number or Statement or Set => throw new InvalidArgumentParseException( - $"{function} is taken of a matrix, as in {example}, and {argument} is not one"), + $"{function} is taken of {what}, as in {example}, and {argument} is not one"), _ => null, }; + // A vector written out, a column or a row, or null where the operand may yet stand for one, as + // MatrixOrUnknown reads it. A matrix written out that is not a vector is refused. + // https://github.com/asc-community/AngouriMath/issues/105 + private static Matrix? VectorOrUnknown(string function, Entity operand) + { + if (MatrixOrUnknown(function, operand, $"{function}([1, 2, 3], [4, 5, 6])", "vectors") is not { } vector) + return null; + if (VectorComponents(vector) is null) + throw new InvalidArgumentParseException( + $"{function} is taken of vectors, and {vector} is a {vector.RowCount} by {vector.ColumnCount} matrix"); + return vector; + } + /// The entries of a vector, written as a column or as a row. private static Entity[] Components(string function, Entity argument) { @@ -120,20 +133,21 @@ internal static Entity Entry(Entity argument, List indices) /// /// dot(a, b): the sum of the products of the components, without conjugating either - /// side, as SymPy's dot and Mathematica's Dot are. + /// side, as SymPy's dot and Mathematica's Dot are; or the node, where an operand + /// is a name that may stand for a vector. /// internal static Entity Dot(Entity left, Entity right) { - var a = Components("dot", left); - var b = Components("dot", right); - if (a.Length != b.Length) - throw new InvalidArgumentParseException( - $"dot is taken of two vectors of one length, and these have {a.Length} and {b.Length} components"); - return Enumerable.Range(0, a.Length).Select(i => a[i] * b[i]).Aggregate((sum, term) => sum + term); + var (a, b) = (VectorOrUnknown("dot", left), VectorOrUnknown("dot", right)); + if (a is null || b is null) + return new DotProductf(left, right); + return DotProductf.Of(a, b) ?? throw new InvalidArgumentParseException( + $"dot is taken of two vectors of one length, and these have {VectorComponents(a)!.Length} and {VectorComponents(b)!.Length} components"); } /// - /// cross(a, b), the vector product in three dimensions, and cross(a), the vector + /// cross(a, b), the vector product in three dimensions, or the node where an operand is a + /// name that may stand for a vector; and cross(a) of a vector written out, the vector /// in the plane that a turns into through a right angle anticlockwise: (-a_2, a_1), /// as Mathematica's Cross of one vector is. So dot(cross(a), b) is the plane's /// pseudo-scalar product a_1 b_2 - a_2 b_1. @@ -148,15 +162,17 @@ internal static Entity Cross(List arguments) $"cross of one vector is its turn through a right angle in the plane, and this vector has {a.Length} components"); return MathS.Vector(-a[1], a[0]); } - var u = Components("cross", arguments[0]); - var v = Components("cross", arguments[1]); - if (u.Length != 3 || v.Length != 3) - throw new InvalidArgumentParseException( - $"cross of two vectors is the vector product in three dimensions, and these have {u.Length} and {v.Length} components"); - return MathS.Vector( - u[1] * v[2] - u[2] * v[1], - u[2] * v[0] - u[0] * v[2], - u[0] * v[1] - u[1] * v[0]); + var (left, right) = (VectorOrUnknown("cross", arguments[0]), VectorOrUnknown("cross", arguments[1])); + if (left is null || right is null) + { + // A vector written out has no vector product unless it has three components, whatever the other one is. + if ((left ?? right) is { } written && VectorComponents(written)!.Length != 3) + throw new InvalidArgumentParseException( + $"cross of two vectors is the vector product in three dimensions, and {written} has {VectorComponents(written)!.Length} components"); + return new CrossProductf(arguments[0], arguments[1]); + } + return CrossProductf.Of(left, right) ?? throw new InvalidArgumentParseException( + $"cross of two vectors is the vector product in three dimensions, and these have {VectorComponents(left)!.Length} and {VectorComponents(right)!.Length} components"); } /// resultant(p, q, x), eliminating x between two polynomials. diff --git a/Sources/AngouriMath/Core/Domains.Classes.cs b/Sources/AngouriMath/Core/Domains.Classes.cs index eeef3834d..59f83da27 100644 --- a/Sources/AngouriMath/Core/Domains.Classes.cs +++ b/Sources/AngouriMath/Core/Domains.Classes.cs @@ -89,6 +89,24 @@ partial record MatrixEntryf internal override Domain DefaultCodomain => Domain.Complex; } + // The scalar product is a number, and the vector product a vector, which has no domain of numbers. + // https://github.com/asc-community/AngouriMath/issues/105 + partial record DotProductf + { + /// + public override Domain Codomain { get; protected init; } = Domain.Complex; + /// + internal override Domain DefaultCodomain => Domain.Complex; + } + + partial record CrossProductf + { + /// + public override Domain Codomain { get; protected init; } = Domain.Any; + /// + internal override Domain DefaultCodomain => Domain.Any; + } + partial record Matrix { /// diff --git a/Sources/AngouriMath/Core/Entity/Omni/Entity.MatrixOperations.Classes.cs b/Sources/AngouriMath/Core/Entity/Omni/Entity.MatrixOperations.Classes.cs index fbe50ec93..e2d0e2b3b 100644 --- a/Sources/AngouriMath/Core/Entity/Omni/Entity.MatrixOperations.Classes.cs +++ b/Sources/AngouriMath/Core/Entity/Omni/Entity.MatrixOperations.Classes.cs @@ -6,10 +6,11 @@ // using System; +using System.Linq; namespace AngouriMath { - // The four operations on a matrix that an expression can name before the matrix is known. A + // The operations on a matrix or on vectors that an expression can name before the matrix is known. A // matrix written out is computed from its entries as soon as it is parsed, as it was without // these nodes; a node is what is left where the argument is not yet a matrix -- a name that // stands for one, det(A) -- and it is computed once the argument becomes a matrix, by @@ -88,5 +89,71 @@ public override Entity Replace(Func func) /// protected override Entity[] InitDirectChildren() => new[] { Argument, Row, Column }; } + + /// + /// The scalar product dot(a, b) of two vectors of one length: the sum of the products of their components, + /// neither side conjugated, as SymPy's dot and Mathematica's Dot are. + /// + /// + /// Computed when both operands are vectors, each a column or a row. Vectors of different lengths, or a matrix that + /// is not a vector, have no scalar product, and the node is left as it is rather than given a value. + /// https://github.com/asc-community/AngouriMath/issues/105 + /// + public sealed partial record DotProductf(Entity Left, Entity Right) : Function + { + private DotProductf New(Entity left, Entity right) => + ReferenceEquals(Left, left) && ReferenceEquals(Right, right) ? this : new(left, right) { Codomain = Codomain }; + /// + public override Entity Replace(Func func) => func(New(Left.Replace(func), Right.Replace(func))); + /// + protected override Entity[] InitDirectChildren() => new[] { Left, Right }; + + /// + /// The sum of the products of the components, or null where the two are not vectors of one length. Written as + /// it was computed when parsed: dot([1, 2], [3, 4]) is 1 * 3 + 2 * 4. + /// + internal static Entity? Of(Matrix left, Matrix right) + => VectorComponents(left) is { } a && VectorComponents(right) is { } b && a.Length == b.Length + ? Enumerable.Range(0, a.Length).Select(i => a[i] * b[i]).Aggregate((sum, term) => sum + term) + : null; + } + + /// + /// The vector product cross(a, b) of two vectors in three dimensions, a column. It is not commutative: + /// cross(b, a) is -cross(a, b), and the operands are never put in another order. + /// + /// + /// Computed when both operands are vectors of three components, each a column or a row. Anything else has no vector + /// product, and the node is left as it is rather than given a value. cross(a) of one vector in the plane is + /// computed from a vector written out only, and has no node. + /// https://github.com/asc-community/AngouriMath/issues/105 + /// + public sealed partial record CrossProductf(Entity Left, Entity Right) : Function + { + private CrossProductf New(Entity left, Entity right) => + ReferenceEquals(Left, left) && ReferenceEquals(Right, right) ? this : new(left, right) { Codomain = Codomain }; + /// + public override Entity Replace(Func func) => func(New(Left.Replace(func), Right.Replace(func))); + /// + protected override Entity[] InitDirectChildren() => new[] { Left, Right }; + + /// + /// The vector product, a column, or null where the two are not vectors of three components. Written as it was + /// computed when parsed: cross([1, 2, 3], [4, 5, 6]) is [2 * 6 - 3 * 5, 3 * 4 - 1 * 6, 1 * 5 - 2 * 4]. + /// + internal static Entity? Of(Matrix left, Matrix right) + => VectorComponents(left) is { Length: 3 } u && VectorComponents(right) is { Length: 3 } v + ? MathS.Vector( + u[1] * v[2] - u[2] * v[1], + u[2] * v[0] - u[0] * v[2], + u[0] * v[1] - u[1] * v[0]) + : null; + } + + /// The components of a vector, written as a column or as a row, or null where the matrix is neither. + internal static Entity[]? VectorComponents(Matrix vector) + => vector.ColumnCount == 1 ? Enumerable.Range(0, vector.RowCount).Select(i => vector[i, 0]).ToArray() + : vector.RowCount == 1 ? Enumerable.Range(0, vector.ColumnCount).Select(j => vector[0, j]).ToArray() + : null; } } diff --git a/Sources/AngouriMath/Core/Serialization/Entity.Serialization.cs b/Sources/AngouriMath/Core/Serialization/Entity.Serialization.cs index 1565db40a..7d80a38df 100644 --- a/Sources/AngouriMath/Core/Serialization/Entity.Serialization.cs +++ b/Sources/AngouriMath/Core/Serialization/Entity.Serialization.cs @@ -68,6 +68,8 @@ [EntityJsonConverter] partial record Entity [EntityJsonConverter] partial record Transposef; [EntityJsonConverter] partial record Tracef; [EntityJsonConverter] partial record MatrixEntryf; + [EntityJsonConverter] partial record DotProductf; + [EntityJsonConverter] partial record CrossProductf; [EntityJsonConverter] partial record Maxf; [EntityJsonConverter] partial record Minf; [EntityJsonConverter] partial record Minusf; diff --git a/Sources/AngouriMath/Core/Transformations/Matching/MatchPattern.cs b/Sources/AngouriMath/Core/Transformations/Matching/MatchPattern.cs index 1b538b55c..4ec2c278c 100644 --- a/Sources/AngouriMath/Core/Transformations/Matching/MatchPattern.cs +++ b/Sources/AngouriMath/Core/Transformations/Matching/MatchPattern.cs @@ -481,6 +481,8 @@ internal abstract bool ETryBuild( [typeof(Entity.Determinantf)] = (1, static c => new Entity.Determinantf(c[0])), [typeof(Entity.Transposef)] = (1, static c => new Entity.Transposef(c[0])), [typeof(Entity.Tracef)] = (1, static c => new Entity.Tracef(c[0])), + [typeof(Entity.DotProductf)] = (2, static c => new Entity.DotProductf(c[0], c[1])), + [typeof(Entity.CrossProductf)] = (2, static c => new Entity.CrossProductf(c[0], c[1])), [typeof(Entity.Alephf)] = (1, static c => new Entity.Alephf(c[0])), [typeof(Entity.Erfcf)] = (1, static c => new Entity.Erfcf(c[0])), [typeof(Entity.Erfif)] = (1, static c => new Entity.Erfif(c[0])), diff --git a/Sources/AngouriMath/Docs/Contributing/WritingARule.md b/Sources/AngouriMath/Docs/Contributing/WritingARule.md index 406a88087..6ad402e40 100644 --- a/Sources/AngouriMath/Docs/Contributing/WritingARule.md +++ b/Sources/AngouriMath/Docs/Contributing/WritingARule.md @@ -110,7 +110,7 @@ itself, and needs no `when:` to say so. It is also strictly more specific than ` the ordering knows about — see below. **Matchable is not the same as buildable.** A pattern can be *matched* against any node type, but a -pattern used as a **replacement** must be one the library can construct: there are **81** such types. +pattern used as a **replacement** must be one the library can construct: there are **83** such types. Two families are deliberately absent, and neither is an oversight: - **binders** — `Lambda`, `Set.ConditionalSet`. They bind a variable, and `DirectChildren` renames it diff --git a/Sources/AngouriMath/Docs/Usage/Syntax.md b/Sources/AngouriMath/Docs/Usage/Syntax.md index 2cae6b2af..23ef6c71e 100644 --- a/Sources/AngouriMath/Docs/Usage/Syntax.md +++ b/Sources/AngouriMath/Docs/Usage/Syntax.md @@ -252,6 +252,16 @@ matrix, and `det(5)` is refused. A name beside a written matrix may stand for a numbers and it is `x ^ 2 - 2` ([#2147](https://github.com/asc-community/AngouriMath/issues/2147)). +`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, +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 +`cross(a, [1, 2])`, it is refused. `cross(a)` of one vector in the plane has no node, and takes a +vector written out ([#105](https://github.com/asc-community/AngouriMath/issues/105)). + `laplacian(f, [x, y, z])` is the sum of the second derivatives of a scalar `f`, `jacobian(F, [x, y])` the matrix of the first derivatives of the components of `F`, a row for each component and a column for each variable, and `hessian(f, [x, y])` the matrix of the second derivatives, the entry in row `i` diff --git a/Sources/AngouriMath/Functions/Compilation/IntoLinq/TensorCompilation.cs b/Sources/AngouriMath/Functions/Compilation/IntoLinq/TensorCompilation.cs index ed1d12692..596ab635d 100644 --- a/Sources/AngouriMath/Functions/Compilation/IntoLinq/TensorCompilation.cs +++ b/Sources/AngouriMath/Functions/Compilation/IntoLinq/TensorCompilation.cs @@ -262,14 +262,16 @@ private sealed class Kit internal MethodInfo Determinant { get; } internal MethodInfo Trace { get; } internal MethodInfo Entry { get; } + internal MethodInfo Dot { get; } + internal MethodInfo Cross { get; } private Kit(Type tensor, Type array, MethodInfo empty, MethodInfo set, MethodInfo add, MethodInfo subtract, MethodInfo multiply, MethodInfo addScalar, MethodInfo subtractScalar, MethodInfo subtractFromScalar, MethodInfo multiplyScalar, MethodInfo divideScalar, MethodInfo power, MethodInfo toArray, MethodInfo fromArray, MethodInfo toScalar, MethodInfo? inverse, MethodInfo? divideByMatrix, MethodInfo? scalarOverMatrix, - MethodInfo transpose, MethodInfo determinant, MethodInfo trace, MethodInfo entry) + MethodInfo transpose, MethodInfo determinant, MethodInfo trace, MethodInfo entry, MethodInfo dot, MethodInfo cross) { - (Transpose, Determinant, Trace, Entry) = (transpose, determinant, trace, entry); + (Transpose, Determinant, Trace, Entry, Dot, Cross) = (transpose, determinant, trace, entry, dot, cross); (Tensor, Array, Empty, Set, Add, Subtract, Multiply, AddScalar, SubtractScalar, SubtractFromScalar, MultiplyScalar, DivideScalar, Power) = (tensor, array, empty, set, add, subtract, multiply, addScalar, subtractScalar, subtractFromScalar, multiplyScalar, divideScalar, power); (ToArray, FromArray, ToScalar, Inverse, DivideByMatrix, ScalarOverMatrix) = (toArray, fromArray, toScalar, inverse, divideByMatrix, scalarOverMatrix); @@ -301,7 +303,9 @@ internal static Kit For(bool field) where TWrapper : struct, IOpera Named, GenTensor>>(a => TensorCompilation.Transpose(a)), Named, T>>(a => TensorCompilation.Determinant(a)), Named, T>>(a => TensorCompilation.Trace(a)), - Named, int, int, T>>((a, i, j) => TensorCompilation.Entry(a, i, j))); + Named, int, int, T>>((a, i, j) => TensorCompilation.Entry(a, i, j)), + Named, GenTensor, T>>((a, b) => TensorCompilation.Dot(a, b)), + Named, GenTensor, GenTensor>>((a, b) => TensorCompilation.Cross(a, b))); } [ConstantField] @@ -685,6 +689,49 @@ public static T Entry(GenTensor a, int row, int column ? a[row - 1, column - 1] : throw new InvalidMatrixOperationException($"A matrix of shape {a.Shape} has no entry at ({row}, {column}): its rows and columns are counted from 1"); + // The components of a vector, a column or a row, by position; the length, or -1 where the matrix is neither. + private static int VectorLength(GenTensor a) where TWrapper : struct, IOperations + => a.Shape[1] == 1 ? a.Shape[0] : a.Shape[0] == 1 ? a.Shape[1] : -1; + + private static T Component(GenTensor a, int i) where TWrapper : struct, IOperations + => a.Shape[1] == 1 ? a[i, 0] : a[0, i]; + + /// + /// The scalar product of two vectors of one length, each a column or a row: the sum of the products of their + /// components, neither side conjugated, as dot is evaluated. + /// https://github.com/asc-community/AngouriMath/issues/105 + /// + /// Either is not a vector, or their lengths differ. + internal static T Dot(GenTensor a, GenTensor b) where TWrapper : struct, IOperations + { + var n = VectorLength(a); + if (n < 0 || n != VectorLength(b)) + throw new InvalidMatrixOperationException($"Matrices of shapes {a.Shape} and {b.Shape} are not two vectors of one length, and have no scalar product"); + var ops = default(TWrapper); + var sum = ops.CreateZero(); + for (var i = 0; i < n; i++) + sum = ops.Add(sum, ops.Multiply(Component(a, i), Component(b, i))); + return sum; + } + + /// + /// The vector product of two vectors of three components, each a column or a row, as a column. + /// https://github.com/asc-community/AngouriMath/issues/105 + /// + /// Either is not a vector of three components. + internal static GenTensor Cross(GenTensor a, GenTensor b) where TWrapper : struct, IOperations + { + if (VectorLength(a) != 3 || VectorLength(b) != 3) + throw new InvalidMatrixOperationException($"Matrices of shapes {a.Shape} and {b.Shape} are not two vectors of three components, and have no vector product"); + var ops = default(TWrapper); + T Minor(int i, int j) => ops.Subtract(ops.Multiply(Component(a, i), Component(b, j)), ops.Multiply(Component(a, j), Component(b, i))); + var result = GenTensor.CreateMatrix(3, 1); + result[0, 0] = Minor(1, 2); + result[1, 0] = Minor(2, 0); + result[2, 0] = Minor(0, 1); + return result; + } + /// A compiled index as the whole number it must be, checked when the delegate is called. /// The index is not a whole number that fits an . public static int WholeIndex(double index) @@ -704,12 +751,25 @@ public static int WholeIndex(Complex index) private static readonly MethodInfo wholeComplexIndex = ((MethodCallExpression)((Expression>)(e => WholeIndex(e))).Body).Method; /// - /// The compiled form of a transpose, a determinant, a trace or an entry, whose first operand is the matrix, or - /// where the node is none of them. + /// The compiled form of a transpose, a determinant, a trace or an entry, whose first operand is the matrix, or of + /// a scalar or a vector product, whose two operands are vectors; or where the node is none + /// of them. /// https://github.com/asc-community/AngouriMath/issues/2147 + /// https://github.com/asc-community/AngouriMath/issues/105 /// internal static Expression? MatrixOperation(Entity node, IReadOnlyList operands, Func convert) { + if (node is Entity.DotProductf or Entity.CrossProductf) + { + foreach (var operand in operands) + 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]); + } if (node is not (Entity.Transposef or Entity.Determinantf or Entity.Tracef or Entity.MatrixEntryf)) return null; if (!kitsByTensor.TryGetValue(operands[0].Type, out var kit)) @@ -917,6 +977,23 @@ private static (int Rows, int Columns)? ShapeOf(Entity expr, Func shape is { Columns: 1, Rows: > 0 } column ? column.Rows : shape is { Rows: 1, Columns: > 0 } row ? row.Columns : null; + foreach (var shape in new[] { a, b }) + if (Known(shape) && !IsVector(shape) + || expr is Entity.CrossProductf && LengthOf(shape) is { } length && length != 3) + throw new InvalidMatrixOperationException( + $"`{expr.Stringize()}` has no value: a {Show(shape)} matrix is not a vector{(expr is Entity.CrossProductf ? " of three components" : "")}"); + if (expr is Entity.DotProductf && LengthOf(a) is { } m && LengthOf(b) is { } n && m != n) + throw new InvalidMatrixOperationException($"`{expr.Stringize()}` has no value: vectors of {m} and {n} components have no scalar product"); + return expr is Entity.CrossProductf ? (3, 1) : null; + } case Entity.MatrixEntryf(var argument, var row, var column): { var a = ShapeOf(argument, isMatrix); diff --git a/Sources/AngouriMath/Functions/Continuous/Differentiation.cs b/Sources/AngouriMath/Functions/Continuous/Differentiation.cs index 4b5a689d1..66ad68fa6 100644 --- a/Sources/AngouriMath/Functions/Continuous/Differentiation.cs +++ b/Sources/AngouriMath/Functions/Continuous/Differentiation.cs @@ -180,6 +180,32 @@ protected override Entity InnerDifferentiate(Variable variable) : new MatrixEntryf(Argument.DerivativeOver(variable), Row, Column); } + // Both products are linear in each operand, so the derivative is the product rule's sum, the operands kept in their + // order, since the vector product is not commutative. An operand that does not vary contributes no term. + // https://github.com/asc-community/AngouriMath/issues/105 + partial record DotProductf + { + /// + protected override Entity InnerDifferentiate(Variable variable) + => ProductRule(Left, Right, variable, static (a, b) => new DotProductf(a, b)); + } + + partial record CrossProductf + { + /// + protected override Entity InnerDifferentiate(Variable variable) + => ProductRule(Left, Right, variable, static (a, b) => new CrossProductf(a, b)); + } + + private static Entity ProductRule(Entity left, Entity right, Variable variable, System.Func product) + => (left.IsConstantIn(variable), right.IsConstantIn(variable)) switch + { + (true, true) => Integer.Zero, + (false, true) => product(left.DerivativeOver(variable), right), + (true, false) => product(left, right.DerivativeOver(variable)), + _ => product(left.DerivativeOver(variable), right) + product(left, right.DerivativeOver(variable)), + }; + partial record Matrix { /// diff --git a/Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver/InvertNode.Classes.cs b/Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver/InvertNode.Classes.cs index a28004ba1..90dc0fea5 100644 --- a/Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver/InvertNode.Classes.cs +++ b/Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver/InvertNode.Classes.cs @@ -51,6 +51,18 @@ partial record MatrixEntryf private protected override IEnumerable? InvertNode(Entity value, Entity x) => null; } + // Neither product determines an operand from its value and the other operand: dot(a, b) = c leaves every + // component of a but one free, and cross(a, b) = c a multiple of b. https://github.com/asc-community/AngouriMath/issues/105 + partial record DotProductf + { + private protected override IEnumerable? InvertNode(Entity value, Entity x) => null; + } + + partial record CrossProductf + { + private protected override IEnumerable? InvertNode(Entity value, Entity x) => null; + } + // Each function and operator processing partial record Sumf { 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 500acd0dd..7217a0173 100644 --- a/Sources/AngouriMath/Functions/Evaluation/Evaluation.Omni/Evaluation.Omni.Classes.cs +++ b/Sources/AngouriMath/Functions/Evaluation/Evaluation.Omni/Evaluation.Omni.Classes.cs @@ -591,15 +591,47 @@ private static Entity OnMatrixArgument(Entity argument, bool isExact, Func e.InnerSimplified(isExact)) : argument.InnerSimplified(isExact)); } + /// + /// An operation on two vectors, carried out where both operands are matrices once simplified, as + /// carries out an operation on one: a vector written in place is kept a vector even + /// with one component, a name beside a written matrix leaves the operation as it is, and a condition or the cases + /// of a piecewise on either operand are carried through. The operands are kept in their order. + /// https://github.com/asc-community/AngouriMath/issues/105 + /// + /// The first operand. + /// The second operand. + /// Whether 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. + private static Entity OnTwoMatrixArguments(Entity left, Entity right, bool isExact, + Func ofMatrices, Func unevaluated) + { + var leftReadsANameAsANumber = left is not Matrix && HasANameOutsideAWrittenMatrix(left); + var rightReadsANameAsANumber = 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 + { + (Providedf(var expression, var predicate), _) => Over(expression, r).Provided(predicate), + (_, Providedf(var expression, var predicate)) => Over(l, expression).Provided(predicate), + (Piecewise piecewise, _) => piecewise.ApplyToValues(value => Over(value, r)), + (_, Piecewise piecewise) => piecewise.ApplyToValues(value => Over(l, value)), + (Matrix a, Matrix b) when !leftReadsANameAsANumber && !rightReadsANameAsANumber + => ofMatrices(a, b) ?? unevaluated(a, b), + _ => unevaluated(leftReadsANameAsANumber && l is Matrix ? left : l, rightReadsANameAsANumber && r is Matrix ? right : r), + }; + return Over(Simplified(left), Simplified(right)); + } + /// /// Whether a name stands somewhere in other than as an entry of a matrix written out, or - /// inside a determinant, a trace or an entry, which are numbers whatever the name is. Such a name may stand for - /// a matrix, and a matrix operation over it is left until it is one. + /// inside a determinant, a trace, an entry or a scalar product, which are numbers whatever the name is. Such a + /// name may stand for a matrix, and a matrix operation over it is left until it is one. /// https://github.com/asc-community/AngouriMath/issues/2147 /// internal static bool HasANameOutsideAWrittenMatrix(Entity expr) { - if (expr is Matrix or Determinantf or Tracef or MatrixEntryf) + if (expr is Matrix or Determinantf or Tracef or MatrixEntryf or DotProductf) return false; if (expr is Variable { IsConstant: false }) return true; @@ -671,6 +703,23 @@ protected override Entity InnerSimplify(bool isExact) } } + 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); + } + + 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); + } + partial record Matrix { private protected override Entity IntrinsicCondition => Boolean.True; diff --git a/Sources/AngouriMath/Functions/Output/Latex/Latex.Omni.Classes.cs b/Sources/AngouriMath/Functions/Output/Latex/Latex.Omni.Classes.cs index 93391ecdb..7f0f2d9f8 100644 --- a/Sources/AngouriMath/Functions/Output/Latex/Latex.Omni.Classes.cs +++ b/Sources/AngouriMath/Functions/Output/Latex/Latex.Omni.Classes.cs @@ -178,6 +178,23 @@ private protected override string LatexizeNode() => $@"{{{Argument.Latexize(Argument.Priority < Priority.Func)}}}_{{{Row.Latexize()},{Column.Latexize()}}}"; } + // The scalar product as a dot and the vector product as a cross, as ISO 80000-2 writes them, each operand in + // parentheses unless it is a name, a number or a call. The dot is the one a product is written with, and so the + // parentheses are kept around anything looser. https://github.com/asc-community/AngouriMath/issues/105 + partial record DotProductf + { + /// + private protected override string LatexizeNode() + => $@"{Left.Latexize(Left.Priority < Priority.Func)} \cdot {Right.Latexize(Right.Priority < Priority.Func)}"; + } + + partial record CrossProductf + { + /// + private protected override string LatexizeNode() + => $@"{Left.Latexize(Left.Priority < Priority.Func)} \times {Right.Latexize(Right.Priority < Priority.Func)}"; + } + partial record Matrix { /// diff --git a/Sources/AngouriMath/Functions/Output/ToString/ToString.Omni.Classes.cs b/Sources/AngouriMath/Functions/Output/ToString/ToString.Omni.Classes.cs index 427b5c13c..21d879f41 100644 --- a/Sources/AngouriMath/Functions/Output/ToString/ToString.Omni.Classes.cs +++ b/Sources/AngouriMath/Functions/Output/ToString/ToString.Omni.Classes.cs @@ -270,6 +270,23 @@ private protected override string StringizeNode() public override string ToString() => Stringize(); } + // https://github.com/asc-community/AngouriMath/issues/105 + partial record DotProductf + { + /// + private protected override string StringizeNode() => $"dot({Left.Stringize()}, {Right.Stringize()})"; + /// + public override string ToString() => Stringize(); + } + + partial record CrossProductf + { + /// + private protected override string StringizeNode() => $"cross({Left.Stringize()}, {Right.Stringize()})"; + /// + public override string ToString() => Stringize(); + } + partial record Matrix { /// diff --git a/Sources/AngouriMath/Functions/Output/ToSympy/ToSympy.Omni.Classes.cs b/Sources/AngouriMath/Functions/Output/ToSympy/ToSympy.Omni.Classes.cs index b1f1ef27e..3428222f0 100644 --- a/Sources/AngouriMath/Functions/Output/ToSympy/ToSympy.Omni.Classes.cs +++ b/Sources/AngouriMath/Functions/Output/ToSympy/ToSympy.Omni.Classes.cs @@ -182,6 +182,18 @@ partial record MatrixEntryf internal override string ToSymPy() => $"({Argument.ToSymPy()})[({Row.ToSymPy()}) - 1, ({Column.ToSymPy()}) - 1]"; } + // SymPy's Matrix.dot conjugates neither side, as this node does not. + // https://github.com/asc-community/AngouriMath/issues/105 + partial record DotProductf + { + internal override string ToSymPy() => $"({Left.ToSymPy()}).dot({Right.ToSymPy()})"; + } + + partial record CrossProductf + { + internal override string ToSymPy() => $"({Left.ToSymPy()}).cross({Right.ToSymPy()})"; + } + partial record Matrix { internal override string ToSymPy() diff --git a/Sources/AngouriMath/Functions/Simplification/Patterns/Patterns.cs b/Sources/AngouriMath/Functions/Simplification/Patterns/Patterns.cs index 4b8be3408..6a08b778b 100644 --- a/Sources/AngouriMath/Functions/Simplification/Patterns/Patterns.cs +++ b/Sources/AngouriMath/Functions/Simplification/Patterns/Patterns.cs @@ -34,9 +34,10 @@ internal static Entity SortAndGroup(Entity original, IEnumerable childre } /// - /// The factors of a product sorted and grouped, unless one of them is a transpose, which is a matrix: matrices do - /// not commute, and AᵀA is not AAᵀ. The product is then left in the order it is written, its other factors - /// included, since a name beside a transpose may stand for a matrix too; a name carries no type to say which + /// The factors of a product sorted and grouped, unless one of them is a transpose, which is a matrix, or a vector + /// product, which is a vector (https://github.com/asc-community/AngouriMath/issues/105). Matrices do not commute: + /// AᵀA is not AAᵀ, and M cross(a, b) is not cross(a, b) M. The product is then left in the order it is written, + /// its other factors included, since a name beside a transpose may stand for a matrix too; a name carries no type to say which /// (https://github.com/asc-community/AngouriMath/issues/1237). /// https://github.com/asc-community/AngouriMath/issues/2147 /// @@ -44,7 +45,8 @@ internal static Entity SortAndGroupFactors(Entity original, TreeAnalyzer.SortLev { var factors = Mulf.LinearChildren(original); for (var i = 0; i < factors.Count; i++) - if (factors[i] is Transposef or Powf(Transposef, _)) + if (factors[i] is Transposef or Powf(Transposef, _) || ProductsOfMatrices.IsAVectorProduct(factors[i]) + || factors[i] is Powf(var powered, _) && ProductsOfMatrices.IsAVectorProduct(powered)) return original; return SortAndGroup(original, factors, level, static (a, b) => a * b); } diff --git a/Sources/AngouriMath/Functions/Simplification/ProductsOfMatrices.cs b/Sources/AngouriMath/Functions/Simplification/ProductsOfMatrices.cs index 1731bb04b..4430dad79 100644 --- a/Sources/AngouriMath/Functions/Simplification/ProductsOfMatrices.cs +++ b/Sources/AngouriMath/Functions/Simplification/ProductsOfMatrices.cs @@ -19,8 +19,10 @@ namespace AngouriMath.Functions /// factors simplified each on its own, in the order they were written. A name beside a transpose is kept in its /// place too, since it may stand for a matrix, and a name carries no type to say whether it does /// (https://github.com/asc-community/AngouriMath/issues/1237). The transpose of a matrix written out is not - /// set aside: simplification carries it out. A determinant, a transpose, a trace or an entry of a name beside a - /// written matrix is set aside whole, since simplifying its argument reads the name as a number. + /// set aside: simplification carries it out. A vector product not yet carried out is a vector, and a product with one + /// in it is set aside as one with a transpose is. A determinant, a transpose, a trace, an entry, or a scalar or a + /// vector product of a name beside a written matrix is set aside whole, since simplifying its argument reads the name + /// as a number. /// https://github.com/asc-community/AngouriMath/issues/2147 /// internal static class ProductsOfMatrices @@ -82,7 +84,8 @@ private static Entity Factor(Entity factor, List<(Variable Name, Entity Product) private static bool HasMatrixOperation(Entity node) { if (node is Transposef { Argument: not Matrix } or Determinantf { Argument: not Matrix } - or Tracef { Argument: not Matrix } or MatrixEntryf { Argument: not Matrix }) + or Tracef { Argument: not Matrix } or MatrixEntryf { Argument: not Matrix } + or DotProductf { Left: not Matrix } or DotProductf { Right: not Matrix } || IsAVectorProduct(node)) return true; var children = node.DirectChildren; for (var i = 0; i < children.Count; i++) @@ -94,19 +97,31 @@ private static bool HasMatrixOperation(Entity node) // An operation on a matrix whose argument has a name beside a written matrix, as det(A [[2, 0], [0, 3]]) has: // simplifying the argument would read the name as a number and multiply it into the entries, and the // operation would then be carried out on that. It is set aside whole until the name is a matrix. + // A scalar or a vector product is set aside the same way where either operand is such an argument. private static bool ReadsANameAsANumber(Entity node) => node is Transposef or Determinantf or Tracef or MatrixEntryf - && node.DirectChildren[0] is not Matrix and var argument + && ReadsANameAsANumberIn(node.DirectChildren[0]) + || node is DotProductf or CrossProductf + && (ReadsANameAsANumberIn(node.DirectChildren[0]) || ReadsANameAsANumberIn(node.DirectChildren[1])); + + private static bool ReadsANameAsANumberIn(Entity argument) + => argument is not Matrix && argument.Nodes.Any(n => n is Matrix) && Entity.HasANameOutsideAWrittenMatrix(argument); - // A transpose, or a product already set aside, among two or more factors that are not numbers. + // A vector product that is not yet carried out, which is a vector, and so a matrix to a product it stands in: + // M cross(a, b) is not cross(a, b) M. https://github.com/asc-community/AngouriMath/issues/105 + internal static bool IsAVectorProduct(Entity node) + => node is CrossProductf { Left: not Matrix } or CrossProductf { Right: not Matrix }; + + // A transpose, a vector product, or a product already set aside, among two or more factors that are not numbers. private static bool IsAProductOfMatrices(Entity product, List<(Variable Name, Entity Product)> products) { var factors = Mulf.LinearChildren(product); var (matrices, others) = (0, 0); foreach (var factor in factors) if (factor is Transposef { Argument: not Matrix } or Powf(Transposef { Argument: not Matrix }, _) + || IsAVectorProduct(factor) || factor is Powf(var poweredBase, _) && IsAVectorProduct(poweredBase) || factor is Variable variable && products.Exists(p => p.Name == variable) || factor is Powf(Variable powered, _) && products.Exists(p => p.Name == powered)) matrices++; diff --git a/Sources/AngouriMath/Functions/Simplification/Simplificator.cs b/Sources/AngouriMath/Functions/Simplification/Simplificator.cs index d7c8e6055..58711a61b 100644 --- a/Sources/AngouriMath/Functions/Simplification/Simplificator.cs +++ b/Sources/AngouriMath/Functions/Simplification/Simplificator.cs @@ -205,9 +205,10 @@ private static Entity FactorsInPrintOrder(Entity.Mulf product) return product; var factors = new System.Collections.Generic.List(); Gather(product, factors); - // A product with a transpose in it is a product of matrices, which do not commute. + // A product with a transpose or a vector product in it is a product of matrices, which do not commute. // https://github.com/asc-community/AngouriMath/issues/2147 - if (factors.Exists(static factor => factor is Entity.Transposef or Entity.Powf(Entity.Transposef, _))) + if (factors.Exists(static factor => factor is Entity.Transposef or Entity.Powf(Entity.Transposef, _) + || ProductsOfMatrices.IsAVectorProduct(factor) || factor is Entity.Powf(var powered, _) && ProductsOfMatrices.IsAVectorProduct(powered))) return product; var ordered = new System.Collections.Generic.List(factors.Count); for (var rank = 0; rank <= 2; rank++) diff --git a/Sources/AngouriMath/Functions/Substitute.cs b/Sources/AngouriMath/Functions/Substitute.cs index 646452c2f..07e3c4ab8 100644 --- a/Sources/AngouriMath/Functions/Substitute.cs +++ b/Sources/AngouriMath/Functions/Substitute.cs @@ -39,6 +39,20 @@ public override Entity Substitute(Entity x, Entity value) => this == x ? value : New(Argument.Substitute(x, value), Row.Substitute(x, value), Column.Substitute(x, value)); } + partial record DotProductf + { + /// + public override Entity Substitute(Entity x, Entity value) + => this == x ? value : New(Left.Substitute(x, value), Right.Substitute(x, value)); + } + + partial record CrossProductf + { + /// + public override Entity Substitute(Entity x, Entity value) + => this == x ? value : New(Left.Substitute(x, value), Right.Substitute(x, value)); + } + partial record Matrix { /// diff --git a/Sources/AngouriMath/Functions/TreeAnalyzer/Sort.Classes.cs b/Sources/AngouriMath/Functions/TreeAnalyzer/Sort.Classes.cs index f36431eb7..a2c0b276b 100644 --- a/Sources/AngouriMath/Functions/TreeAnalyzer/Sort.Classes.cs +++ b/Sources/AngouriMath/Functions/TreeAnalyzer/Sort.Classes.cs @@ -74,6 +74,18 @@ private protected override string SortHashName(SortLevel level) => Choice(level, "entry_", "entry_", "entry_"); } + partial record DotProductf + { + private protected override string SortHashName(SortLevel level) + => Choice(level, "dot_", "dot_", "dot_"); + } + + partial record CrossProductf + { + private protected override string SortHashName(SortLevel level) + => Choice(level, "cross_", "cross_", "cross_"); + } + partial record Matrix { private protected override string SortHashName(SortLevel level) diff --git a/Sources/MCP/AngouriMath.Mcp/Resources.cs b/Sources/MCP/AngouriMath.Mcp/Resources.cs index af68e60a0..7f9785441 100644 --- a/Sources/MCP/AngouriMath.Mcp/Resources.cs +++ b/Sources/MCP/AngouriMath.Mcp/Resources.cs @@ -110,9 +110,10 @@ upper incomplete gamma function apply lambda` - matrices and vectors: `det transpose trace dot cross resultant`, computed from a matrix or a vector written out, `[1, 2]` being a column and `[[1, 2], [3, 4]]` a - matrix. `det(A)`, `transpose(A)`, `trace(A)` and the entry `A[k, l]` (counted from 1) - of a name are nodes, carried out once the name is substituted by a matrix. - `cross(a, b)` is the vector product in space and `cross([x, y])` is `[-y, x]`; + matrix. `det(A)`, `transpose(A)`, `trace(A)`, the entry `A[k, l]` (counted from 1), + `dot(a, b)` and `cross(a, b)` of a name are nodes, carried out once the name is + substituted by a matrix or a vector. `cross(a, b)` is the vector product in space, + its operands kept in their order, and `cross([x, y])` of a vector written out is `[-y, x]`; `resultant(p, q, x)` eliminates `x` - `forwarddifference(f, k)`, which is `f(k + 1) - f(k)` once parsed - `laplacian(f, [x, y])`, `jacobian(F, [x, y])` and `hessian(f, [x, y])`, made of diff --git a/Sources/Tests/McpUnitTests/ParsingTest.cs b/Sources/Tests/McpUnitTests/ParsingTest.cs index a00eddfb9..4451f2fb5 100644 --- a/Sources/Tests/McpUnitTests/ParsingTest.cs +++ b/Sources/Tests/McpUnitTests/ParsingTest.cs @@ -60,7 +60,7 @@ public void TheSyntaxDocumentNamesEveryFunctionTheGrammarAccepts(string name) } catch (InvalidArgumentParseException) { - // A function of a matrix or a vector written out, which x is not: dot(x). + // A function of a vector written out, which x is not: cross(x). } var syntax = Resources.Read("angourimath://syntax")!; Assert.True(Regex.IsMatch(syntax, $@"(? + /// 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. + /// #105 + /// + [Trait("Area", "Common")] + public sealed class DotAndCrossNodesTest + { + private static readonly Complex[][] Vectors = + { + new Complex[] { 1, 2, 3 }, + new Complex[] { -1.5, 0.25, -4 }, + new Complex[] { new(1, 2), -3, new(0, -1) }, + new Complex[] { new(2.5, 0.5), new(-1, 1), 2 }, + }; + + private static Entity.Matrix Column(Complex[] v) => MathS.Vector(v.Select(c => (Entity)c).ToArray()); + + private static Entity.Matrix Row(Complex[] v) => MathS.Matrix(1, v.Length, (_, c) => (Entity)v[c]); + + private static Complex Value(Entity e) => e.EvalNumerical().ToNumerics(); + + 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 void Near(Complex[] expected, Complex[] actual) + { + Assert.Equal(expected.Length, actual.Length); + for (var i = 0; i < expected.Length; i++) + Near(expected[i], actual[i]); + } + + // The definitions, not the library's code: neither side of the scalar product is conjugated. + private static Complex Dot(Complex[] a, Complex[] b) => a.Zip(b, (x, y) => x * y).Aggregate(Complex.Zero, (s, t) => s + t); + + 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[] Components(Entity value) + { + var column = Assert.IsType(value); + Assert.Equal(1, column.ColumnCount); + return Enumerable.Range(0, column.RowCount).Select(i => Value(column[i, 0])).ToArray(); + } + + [Theory] + [InlineData("dot(a, b)", typeof(Entity.DotProductf))] + [InlineData("cross(a, b)", typeof(Entity.CrossProductf))] + [InlineData("dot([1, 2, 3], b)", typeof(Entity.DotProductf))] + [InlineData("cross(a, [1, 2, 3])", typeof(Entity.CrossProductf))] + [InlineData("dot(a + b, c)", typeof(Entity.DotProductf))] + [InlineData("cross(cross(a, b), c)", typeof(Entity.CrossProductf))] + [InlineData("dot(transpose(A) * a, b)", typeof(Entity.DotProductf))] + // A name beside a written vector may stand for a matrix, so the operand is not read as a number. + [InlineData("dot(x * [1, 2], [3, 4])", typeof(Entity.DotProductf))] + public void ANameForAVectorParsesToTheNode(string input, Type node) + => Assert.IsType(node, input.ToEntity()); + + [Theory] + [InlineData("dot(a, b)")] + [InlineData("cross(a, b)")] + [InlineData("cross(b, a) * 2 + dot(a, c) * d")] + [InlineData("dot(cross(a, b), c)")] + [InlineData("cross(a, [1, 2, 3])")] + [InlineData("dot(x * [1, 2], [3, 4])")] + [InlineData("M * cross(a, b)")] + public void PrintingRoundTrips(string input) + { + var parsed = input.ToEntity(); + Assert.Equal(parsed, parsed.Stringize().ToEntity()); + } + + // Vectors written out are computed as they are parsed, as they were without the nodes, and print as they did. + [Theory] + [InlineData("dot([1, 2, 3], [4, 5, 6])", "1 * 4 + 2 * 5 + 3 * 6", "32")] + [InlineData("dot([x, y, z], [1, 0, 0])", "x * 1 + y * 0 + z * 0", "x")] + [InlineData("dot([1, i], [i, 1])", "1 * i + i * 1", "2i")] + [InlineData("dot([1, 2]T, [3, 4])", "1 * 3 + 2 * 4", "11")] + [InlineData("cross([0, 0, w], [x, y, z])", "[0 * z - w * y, w * x - 0 * z, 0 * y - 0 * x]", "[-w * y, w * x, 0]")] + [InlineData("cross([1, 2, 3], [4, 5, 6])", "[2 * 6 - 3 * 5, 3 * 4 - 1 * 6, 1 * 5 - 2 * 4]", "[-3, 6, -3]")] + public void VectorsWrittenOutAreComputedWhenParsed(string input, string parsed, string simplified) + { + var entity = input.ToEntity(); + Assert.Equal(parsed, entity.Stringize()); + Assert.Equal(simplified, entity.InnerSimplified.Stringize()); + Assert.Equal(simplified, entity.Simplify().Stringize()); + } + + [Fact] + public void TheScalarProductOfSubstitutedVectorsIsTheirScalarProduct() + { + Assert.Equal(32, "dot(a, b)".ToEntity().Substitute("a", "[1, 2, 3]").Substitute("b", "[4, 5, 6]").Simplify()); + foreach (var a in Vectors) + foreach (var b in Vectors) + { + var expected = Dot(a, b); + Near(expected, Value("dot(a, b)".ToEntity().Substitute("a", Column(a)).Substitute("b", Column(b)).Evaled)); + // A row is a vector too, as it is written out. + Near(expected, Value("dot(a, b)".ToEntity().Substitute("a", Row(a)).Substitute("b", Column(b)).Simplify())); + } + } + + [Fact] + public void TheVectorProductOfSubstitutedVectorsIsTheirVectorProduct() + { + var crossed = "cross(W, r)".ToEntity().Substitute("W", "[0, 0, w]").Substitute("r", "[x, y, z]").Simplify(); + Assert.Equal("[-w * y, w * x, 0]".ToEntity(), crossed); + foreach (var u in Vectors) + foreach (var v in Vectors) + { + Near(Cross(u, v), Components("cross(a, b)".ToEntity().Substitute("a", Column(u)).Substitute("b", Column(v)).Evaled)); + Near(Cross(u, v), Components("cross(a, b)".ToEntity().Substitute("a", Row(u)).Substitute("b", Row(v)).Simplify())); + } + } + + // The vector product is perpendicular to both its operands, the scalar product being taken without conjugation. + [Fact] + public void TheVectorProductIsPerpendicularToBothOperands() + { + foreach (var u in Vectors) + foreach (var v in Vectors) + { + Entity At(string e) => e.ToEntity().Substitute("a", Column(u)).Substitute("b", Column(v)).Evaled; + Near(0, Value(At("dot(cross(a, b), a)"))); + Near(0, Value(At("dot(b, cross(a, b))"))); + } + } + + // A number is not a vector, a matrix that is not one is refused, and a vector written out must be able to have a + // value whatever the other operand turns out to be. + [Theory] + [InlineData("dot(5, a)")] + [InlineData("dot(a, x = 1)")] + [InlineData("cross(a, {1, 2})")] + [InlineData("dot([[1, 2], [3, 4]], a)")] + [InlineData("cross(a, [1, 2])")] + [InlineData("cross([1, 2, 3, 4], a)")] + [InlineData("dot([1, 2], [1, 2, 3])")] + [InlineData("cross([1, 2], [3, 4])")] + [InlineData("cross(a)")] + public void WhatIsNoVectorOrHasNoProductIsRefused(string input) + => Assert.Throws(() => input.ToEntity()); + + // No product: the node is left, never a number, as a determinant of a matrix that is not square is. + [Theory] + [InlineData("dot(a, b)", "[1, 2, 3]", "[4, 5]")] + [InlineData("dot(a, b)", "[[1, 2], [3, 4]]", "[4, 5]")] + [InlineData("dot(a, b)", "5", "[4, 5]")] + [InlineData("cross(a, b)", "[1, 2]", "[4, 5]")] + [InlineData("cross(a, b)", "[1, 2, 3]", "[4, 5, 6, 7]")] + [InlineData("cross(a, b)", "[1, 2, 3]", "7")] + public void WhatHasNoProductIsLeftUnevaluated(string input, string a, string b) + { + var node = input.ToEntity().GetType(); + var substituted = input.ToEntity().Substitute("a", a).Substitute("b", b); + Assert.IsType(node, substituted.Evaled); + Assert.IsType(node, substituted.InnerSimplified); + Assert.IsType(node, substituted.Simplify()); + } + + // cross(b, a) is -cross(a, b): nothing may put the operands in the other order, or read the two as one. + [Fact] + public void TheOperandsOfTheVectorProductKeepTheirOrder() + { + var ab = "cross(a, b)".ToEntity(); + var ba = "cross(b, a)".ToEntity(); + Assert.NotEqual(ab, ba); + Assert.Equal(ab, ab.Simplify()); + Assert.Equal(ab, ab.InnerSimplified); + Assert.Equal(ba, ba.Simplify()); + Assert.Equal(ba, ba.InnerSimplified); + Assert.NotEqual(ab.Simplify(), ba.Simplify()); + + var sum = "cross(a, b) + cross(b, a)".ToEntity(); + foreach (var form in new[] { sum.Simplify(), sum.InnerSimplified, sum.Evaled }) + { + Assert.NotEqual("2 * cross(a, b)".ToEntity(), form); + Assert.NotEqual("2 * cross(b, a)".ToEntity(), form); + Assert.Contains(ab, form.Nodes); + Assert.Contains(ba, form.Nodes); + // And the sum is the zero vector once the operands are vectors. + Near(new Complex[] { 0, 0, 0 }, Components(form.Substitute("a", Column(Vectors[2])).Substitute("b", Column(Vectors[3])).Evaled)); + } + Assert.Equal(Entity.Number.Integer.Zero, "cross(a, b) - cross(a, b)".ToEntity().Simplify()); + } + + // A vector product is a vector, and does not commute with a matrix: M cross(a, b) has a value where + // cross(a, b) M has none, and simplification must keep the product in its order. + [Theory] + [InlineData("M * cross(a, b)")] + [InlineData("2 * M * cross(a, b)")] + [InlineData("M * cross(a, b) * k")] + [InlineData("M * cross(a, b) - cross(b, a)")] + public void AProductWithAVectorProductKeepsItsOrder(string input) + { + var expr = input.ToEntity(); + var m = MathS.Matrix(new Entity[,] { { 1, -2, 0.5 }, { 3, "1 + i".ToEntity(), -1 }, { 0, 2, -4 } }); + Entity At(Entity e) => e.Substitute("M", m).Substitute("a", Column(Vectors[1])).Substitute("b", Column(Vectors[2])).Substitute("k", 3).Evaled; + var expected = Components(At(expr)); + foreach (var form in new[] { expr.Simplify(), expr.InnerSimplified }) + Near(expected, Components(At(form))); + } + + // Linear in each operand: the product rule, the operands kept in their order. + [Fact] + public void TheProductsAreDifferentiatedByTheProductRule() + { + var (a, b) = (Vectors[1], Vectors[2]); + foreach (var x in new Complex[] { 2, -1.5 }) + { + Entity At(Entity e) => e.Substitute("a", Column(a)).Substitute("b", Column(b)).Substitute("x", x).Evaled; + // d/dx dot(x^2 a, x b) = 3 x^2 dot(a, b) + Near(3 * x * x * Dot(a, b), Value(At("dot(x^2 * a, x * b)".ToEntity().Differentiate("x")))); + // d/dx cross(x^2 a, x b) = 3 x^2 cross(a, b) + Near(Cross(a, b).Select(c => 3 * x * x * c).ToArray(), Components(At("cross(x^2 * a, x * b)".ToEntity().Differentiate("x")))); + } + Assert.Equal(Entity.Number.Integer.Zero, "dot(a, b)".ToEntity().Differentiate("x")); + Assert.Equal("cross(a, b)".ToEntity(), "cross(x * a, b)".ToEntity().Differentiate("x").Simplify()); + } + + [Fact] + public void TheNodesPrintToLatexAndSympy() + { + Assert.Equal(@"a \cdot b", "dot(a, b)".ToEntity().Latexize()); + Assert.Equal(@"a \times b", "cross(a, b)".ToEntity().Latexize()); + Assert.Equal(@"\left(a+b\right) \cdot c", "dot(a + b, c)".ToEntity().Latexize()); + var sympy = MathS.ToSympyCode("dot(a, b) + cross(a, b)"); + Assert.Contains("(a).dot(b)", sympy); + Assert.Contains("(a).cross(b)", sympy); + } + + [Fact] + public void TheConstructorsBuildTheNodes() + { + Assert.Equal("dot(a, b)".ToEntity(), MathS.Matrices.DotProduct("a", "b")); + Assert.Equal("cross(a, b)".ToEntity(), MathS.Matrices.CrossProduct("a", "b")); + // Over vectors written out the node is computed when simplified, to the value parsing gives. + Assert.Equal("dot([1, 2], [3, 4])".ToEntity().Simplify(), MathS.Matrices.DotProduct("[1, 2]", "[3, 4]").Simplify()); + Assert.Equal("cross([1, 2, 3], [4, 5, 6])".ToEntity().Simplify(), MathS.Matrices.CrossProduct("[1, 2, 3]", "[4, 5, 6]").Simplify()); + } + + // Compiled, each compared with evaluation at the same vectors. + [Fact] + public void TheProductsCompile() + { + var dotOverVectors = "dot(a, b)".ToEntity().Compile("a", "b"); + var crossOverVectors = "cross(a, b)".ToEntity().Compile("a", "b"); + var dotOverColumns = "dot(a, b)".ToEntity().Compile("a", "b"); + foreach (var u in Vectors) + foreach (var v in Vectors) + { + Entity At(string e) => e.ToEntity().Substitute("a", Column(u)).Substitute("b", Column(v)).Evaled; + Near(Value(At("dot(a, b)")), dotOverVectors(u, v)); + Near(Components(At("cross(a, b)")), crossOverVectors(u, v)); + var column = new Complex[u.Length, 1]; + var row = new Complex[1, v.Length]; + for (var i = 0; i < u.Length; i++) + (column[i, 0], row[0, i]) = (u[i], v[i]); + Near(Dot(u, v), dotOverColumns(column, row)); + } + var overReals = "dot(a, b)".ToEntity().Compile("a", "b"); + Assert.Equal(32, overReals(new double[] { 1, 2, 3 }, new double[] { 4, 5, 6 }), 12); + var crossOverReals = "cross(a, b)".ToEntity().Compile("a", "b"); + Assert.Equal(new double[,] { { -6 }, { 2 }, { 0 } }, crossOverReals(new double[,] { { 0 }, { 0 }, { 2 } }, new double[,] { { 1 }, { 3 }, { 5 } })); + // 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); + } + + [Fact] + public void WhatCannotBeComputedIsRefusedWhenCompilingOrCalled() + { + var dot = "dot(a, b)".ToEntity().Compile("a", "b"); + Assert.Throws(() => dot(new double[] { 1, 2, 3 }, new double[] { 4, 5 })); + var cross = "cross(a, b)".ToEntity().Compile("a", "b"); + Assert.Throws(() => cross(new double[] { 1, 2 }, new double[] { 4, 5 })); + var dotOfMatrices = "dot(a, b)".ToEntity().Compile("a", "b"); + Assert.Throws(() => dotOfMatrices(new double[,] { { 1, 2 }, { 3, 4 } }, new double[,] { { 1, 2 }, { 3, 4 } })); + // Shapes written into the expression are checked when compiling. + Assert.Throws(() => MathS.Matrices.DotProduct("[x, 2]", "[1, 2, 3]").Compile("x")); + Assert.Throws(() => MathS.Matrices.CrossProduct("[x, 2]", "a").Compile("x", "a")); + // A number is not a vector operand. + Assert.Throws(() => "dot(a, b)".ToEntity().Compile("a", "b")); + Assert.Throws(() => "cross(a, b)".ToEntity().Compile("a", "b")); + } + } +} diff --git a/Sources/Tests/UnitTests/Common/PublicApi.txt b/Sources/Tests/UnitTests/Common/PublicApi.txt index 65965ac6b..a256cd1f3 100644 --- a/Sources/Tests/UnitTests/Common/PublicApi.txt +++ b/Sources/Tests/UnitTests/Common/PublicApi.txt @@ -964,6 +964,26 @@ AngouriMath.Entity+Cotanf.ToString() : System.String AngouriMath.Entity+Cotanf.ctor(AngouriMath.Entity) AngouriMath.Entity+Cotanf.op_Equality(AngouriMath.Entity+Cotanf, AngouriMath.Entity+Cotanf) : System.Boolean AngouriMath.Entity+Cotanf.op_Inequality(AngouriMath.Entity+Cotanf, AngouriMath.Entity+Cotanf) : System.Boolean +AngouriMath.Entity+CrossProductf.$() : AngouriMath.Entity+CrossProductf +AngouriMath.Entity+CrossProductf.Codomain { } : AngouriMath.Core.Domain +AngouriMath.Entity+CrossProductf.Deconstruct(AngouriMath.Entity&, AngouriMath.Entity&) : System.Void +AngouriMath.Entity+CrossProductf.EqualityContract { } : System.Type +AngouriMath.Entity+CrossProductf.Equals(AngouriMath.Entity+CrossProductf) : System.Boolean +AngouriMath.Entity+CrossProductf.Equals(AngouriMath.Entity+Function) : System.Boolean +AngouriMath.Entity+CrossProductf.Equals(System.Object) : System.Boolean +AngouriMath.Entity+CrossProductf.GetHashCode() : System.Int32 +AngouriMath.Entity+CrossProductf.InitDirectChildren() : AngouriMath.Entity[] +AngouriMath.Entity+CrossProductf.InnerDifferentiate(AngouriMath.Entity+Variable) : AngouriMath.Entity +AngouriMath.Entity+CrossProductf.InnerSimplify(System.Boolean) : AngouriMath.Entity +AngouriMath.Entity+CrossProductf.Left { } : AngouriMath.Entity +AngouriMath.Entity+CrossProductf.PrintMembers(System.Text.StringBuilder) : System.Boolean +AngouriMath.Entity+CrossProductf.Replace(System.Func) : AngouriMath.Entity +AngouriMath.Entity+CrossProductf.Right { } : AngouriMath.Entity +AngouriMath.Entity+CrossProductf.Substitute(AngouriMath.Entity, AngouriMath.Entity) : AngouriMath.Entity +AngouriMath.Entity+CrossProductf.ToString() : System.String +AngouriMath.Entity+CrossProductf.ctor(AngouriMath.Entity, AngouriMath.Entity) +AngouriMath.Entity+CrossProductf.op_Equality(AngouriMath.Entity+CrossProductf, AngouriMath.Entity+CrossProductf) : System.Boolean +AngouriMath.Entity+CrossProductf.op_Inequality(AngouriMath.Entity+CrossProductf, AngouriMath.Entity+CrossProductf) : System.Boolean AngouriMath.Entity+Derivativef.$() : AngouriMath.Entity+Derivativef AngouriMath.Entity+Derivativef.Codomain { } : AngouriMath.Core.Domain AngouriMath.Entity+Derivativef.Deconstruct(AngouriMath.Entity&, AngouriMath.Entity&, System.Int32&) : System.Void @@ -1065,6 +1085,26 @@ AngouriMath.Entity+DivisorSigmaf.ToString() : System.String AngouriMath.Entity+DivisorSigmaf.ctor(AngouriMath.Entity, AngouriMath.Entity) AngouriMath.Entity+DivisorSigmaf.op_Equality(AngouriMath.Entity+DivisorSigmaf, AngouriMath.Entity+DivisorSigmaf) : System.Boolean AngouriMath.Entity+DivisorSigmaf.op_Inequality(AngouriMath.Entity+DivisorSigmaf, AngouriMath.Entity+DivisorSigmaf) : System.Boolean +AngouriMath.Entity+DotProductf.$() : AngouriMath.Entity+DotProductf +AngouriMath.Entity+DotProductf.Codomain { } : AngouriMath.Core.Domain +AngouriMath.Entity+DotProductf.Deconstruct(AngouriMath.Entity&, AngouriMath.Entity&) : System.Void +AngouriMath.Entity+DotProductf.EqualityContract { } : System.Type +AngouriMath.Entity+DotProductf.Equals(AngouriMath.Entity+DotProductf) : System.Boolean +AngouriMath.Entity+DotProductf.Equals(AngouriMath.Entity+Function) : System.Boolean +AngouriMath.Entity+DotProductf.Equals(System.Object) : System.Boolean +AngouriMath.Entity+DotProductf.GetHashCode() : System.Int32 +AngouriMath.Entity+DotProductf.InitDirectChildren() : AngouriMath.Entity[] +AngouriMath.Entity+DotProductf.InnerDifferentiate(AngouriMath.Entity+Variable) : AngouriMath.Entity +AngouriMath.Entity+DotProductf.InnerSimplify(System.Boolean) : AngouriMath.Entity +AngouriMath.Entity+DotProductf.Left { } : AngouriMath.Entity +AngouriMath.Entity+DotProductf.PrintMembers(System.Text.StringBuilder) : System.Boolean +AngouriMath.Entity+DotProductf.Replace(System.Func) : AngouriMath.Entity +AngouriMath.Entity+DotProductf.Right { } : AngouriMath.Entity +AngouriMath.Entity+DotProductf.Substitute(AngouriMath.Entity, AngouriMath.Entity) : AngouriMath.Entity +AngouriMath.Entity+DotProductf.ToString() : System.String +AngouriMath.Entity+DotProductf.ctor(AngouriMath.Entity, AngouriMath.Entity) +AngouriMath.Entity+DotProductf.op_Equality(AngouriMath.Entity+DotProductf, AngouriMath.Entity+DotProductf) : System.Boolean +AngouriMath.Entity+DotProductf.op_Inequality(AngouriMath.Entity+DotProductf, AngouriMath.Entity+DotProductf) : System.Boolean AngouriMath.Entity+DoubleFactorialf.$() : AngouriMath.Entity+DoubleFactorialf AngouriMath.Entity+DoubleFactorialf.Argument { } : AngouriMath.Entity AngouriMath.Entity+DoubleFactorialf.Codomain { } : AngouriMath.Core.Domain @@ -3518,7 +3558,9 @@ AngouriMath.MathS+Matrices+Direction.Horizontal : AngouriMath.MathS+Matrices+Dir AngouriMath.MathS+Matrices+Direction.Vertical : AngouriMath.MathS+Matrices+Direction AngouriMath.MathS+Matrices+Direction.value__ : System.Int32 AngouriMath.MathS+Matrices.Concat(AngouriMath.MathS+Matrices+Direction, AngouriMath.Entity+Matrix[]) : AngouriMath.Entity+Matrix +AngouriMath.MathS+Matrices.CrossProduct(AngouriMath.Entity, AngouriMath.Entity) : AngouriMath.Entity AngouriMath.MathS+Matrices.Determinant(AngouriMath.Entity) : AngouriMath.Entity +AngouriMath.MathS+Matrices.DotProduct(AngouriMath.Entity, AngouriMath.Entity) : AngouriMath.Entity AngouriMath.MathS+Matrices.Entry(AngouriMath.Entity, AngouriMath.Entity, AngouriMath.Entity) : AngouriMath.Entity AngouriMath.MathS+Matrices.Matrix(System.Int32, System.Int32, AngouriMath.Entity[]) : AngouriMath.Entity+Matrix AngouriMath.MathS+Matrices.PointwiseMultiplication(AngouriMath.Entity+Matrix, AngouriMath.Entity+Matrix) : AngouriMath.Entity+Matrix @@ -3856,11 +3898,13 @@ class AngouriMath.Entity+ContinuousNode class AngouriMath.Entity+Cosecantf class AngouriMath.Entity+Cosf class AngouriMath.Entity+Cotanf +class AngouriMath.Entity+CrossProductf class AngouriMath.Entity+Derivativef class AngouriMath.Entity+Determinantf class AngouriMath.Entity+Divf class AngouriMath.Entity+Dividesf class AngouriMath.Entity+DivisorSigmaf +class AngouriMath.Entity+DotProductf class AngouriMath.Entity+DoubleFactorialf class AngouriMath.Entity+Eif class AngouriMath.Entity+Equalsf diff --git a/Sources/Tests/UnitTests/Convenience/MatrixFunctionsInAnExpressionTest.cs b/Sources/Tests/UnitTests/Convenience/MatrixFunctionsInAnExpressionTest.cs index a03e15280..65612892f 100644 --- a/Sources/Tests/UnitTests/Convenience/MatrixFunctionsInAnExpressionTest.cs +++ b/Sources/Tests/UnitTests/Convenience/MatrixFunctionsInAnExpressionTest.cs @@ -65,14 +65,15 @@ public void TheVectorProductIsPerpendicularToBothFactors() /// /// A number, a matrix of the wrong shape, or vectors of different lengths have nothing to /// be, and are refused at parsing rather than read as something else. A symbol is not - /// refused by det and transpose, which are nodes over a name for a matrix - /// (MatrixOperationNodesTest); dot, cross and resultant have no node. + /// refused by det, transpose, dot and cross, which are nodes over a name for a matrix or a vector + /// (MatrixOperationNodesTest, DotAndCrossNodesTest); cross of one vector and resultant have no node. /// [Theory] [InlineData("det(5)")] [InlineData("det([[1, 2, 3], [4, 5, 6]])")] [InlineData("transpose(2)")] - [InlineData("dot(A, [1, 2])")] + [InlineData("dot(5, [1, 2])")] + [InlineData("cross(A, [1, 2])")] [InlineData("dot([1, 2], [1, 2, 3])")] [InlineData("dot([[1, 2], [3, 4]], [1, 2])")] [InlineData("cross([1, 2], [3, 4])")] diff --git a/Sources/Tests/UnitTests/Convenience/StringizeRoundTripTest.cs b/Sources/Tests/UnitTests/Convenience/StringizeRoundTripTest.cs index 4c0335123..b46f8d169 100644 --- a/Sources/Tests/UnitTests/Convenience/StringizeRoundTripTest.cs +++ b/Sources/Tests/UnitTests/Convenience/StringizeRoundTripTest.cs @@ -116,6 +116,8 @@ public void TheNodesWithoutAnOperatorSpellingPrintAsTheirFunction(string source) [InlineData("limit(x, x, 0)")] [InlineData("limitleft(x, x, 0)")] [InlineData("limitright(x, x, 0)")] + [InlineData("dot(a, b)")] + [InlineData("cross(a, b)")] public void FunctionsRoundTrip(string source) => AssertRoundTrip(source); [Theory] diff --git a/Sources/Tests/UnitTests/Core/Transformations/RuleAuthoringGuideTest.cs b/Sources/Tests/UnitTests/Core/Transformations/RuleAuthoringGuideTest.cs index 44a6c93b9..4020656d0 100644 --- a/Sources/Tests/UnitTests/Core/Transformations/RuleAuthoringGuideTest.cs +++ b/Sources/Tests/UnitTests/Core/Transformations/RuleAuthoringGuideTest.cs @@ -79,7 +79,7 @@ public void TheIdentityIsNotTheName() [Fact] public void ThePatternLanguage() - => Stated(81, MatchPattern.BuildableNodeTypes.Count, "the number of buildable node types"); + => Stated(83, MatchPattern.BuildableNodeTypes.Count, "the number of buildable node types"); [Fact] public void ReplacementAPatternOrCode()