From 0b99f40c172df74f249bedb619a06eb7f70ff1cd Mon Sep 17 00:00:00 2001 From: Rafael Vuijk <133344302+Rafael-SOWNet@users.noreply.github.com> Date: Fri, 30 Oct 2026 19:59:47 +0100 Subject: [PATCH 1/3] Dimensional analysis: MathS.Dimensions.Of and DimensionlessGroups Given the dimension of each variable over the seven SI base dimensions, MathS.Dimensions.Of says whether a formula is physically meaningful, what dimension it has, and which subexpression breaks it and why. The verdict is three-valued: Undetermined, for an undeclared variable, a node the check does not read, or a dimensional base raised to an unknown power, is not a guess. Nothing is simplified first, and a literal 0 or oo fits any dimension where it is added or compared. MathS.Dimensions.DimensionlessGroups gives a basis of the Buckingham pi groups from the exact null space of the dimension matrix, in smallest whole powers, each checked to be dimensionless before it is returned. The dimension map is passed rather than attached to variables, so printing, parsing and simplification are unchanged and the type layer of #1237 is not pre-empted. No clause of Packaging.md section 4 fires, so it is kernel code. No existing answer changes. Measured: UnitTests 18258 passed, 13 skipped, 0 failed (net10.0); FSharpWrapperUnitTests 134 passed; kernel builds warning-free on netstandard2.0, net8.0 and net10.0. Co-Authored-By: Claude Opus 5.5 --- Sources/.editorconfig | 9 + .../Convenience/MathS.Dimensions.cs | 137 +++++++++++++ .../Functions/Dimensions/Dimension.cs | 174 ++++++++++++++++ .../Functions/Dimensions/DimensionAnalysis.cs | 191 ++++++++++++++++++ .../Functions/Dimensions/DimensionCheck.cs | 64 ++++++ .../Dimensions/DimensionlessGroups.cs | 112 ++++++++++ Sources/Tests/UnitTests/Common/PublicApi.txt | 54 +++++ .../UnitTests/Convenience/DimensionsTest.cs | 155 ++++++++++++++ 8 files changed, 896 insertions(+) create mode 100644 Sources/AngouriMath/Convenience/MathS.Dimensions.cs create mode 100644 Sources/AngouriMath/Functions/Dimensions/Dimension.cs create mode 100644 Sources/AngouriMath/Functions/Dimensions/DimensionAnalysis.cs create mode 100644 Sources/AngouriMath/Functions/Dimensions/DimensionCheck.cs create mode 100644 Sources/AngouriMath/Functions/Dimensions/DimensionlessGroups.cs create mode 100644 Sources/Tests/UnitTests/Convenience/DimensionsTest.cs diff --git a/Sources/.editorconfig b/Sources/.editorconfig index d1b69658b..b34c0f936 100644 --- a/Sources/.editorconfig +++ b/Sources/.editorconfig @@ -1163,6 +1163,15 @@ file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed [Tests/UnitTests/Convenience/ShadersTest.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/Dimensions/*.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/Convenience/MathS.Dimensions.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/Convenience/DimensionsTest.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/Convenience/PrimeFactorizationNodeTest.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.Dimensions.cs b/Sources/AngouriMath/Convenience/MathS.Dimensions.cs new file mode 100644 index 000000000..076ffd3ac --- /dev/null +++ b/Sources/AngouriMath/Convenience/MathS.Dimensions.cs @@ -0,0 +1,137 @@ +// +// 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. +// + + + +namespace AngouriMath +{ + using static Entity; + + partial class MathS + { + /// + /// Dimensional analysis: whether a formula is physically meaningful, what kind of + /// quantity it produces, and which combinations of its variables are pure numbers. + /// + /// + /// + /// A variable is a symbol, and nothing in an says that v + /// is a speed. The caller says so, with a map from each variable to its + /// , and the check reads the formula against it. The map is + /// passed rather than attached to the variables, so the same expression can be read + /// under different assignments, and nothing about how an expression prints, parses or + /// simplifies changes. + /// + /// + /// This complements a units library rather than replacing one. UnitsNet and its kind + /// check a value: a length divided by a time is a speed. Neither can look at + /// sqrt(2 g h) and say whether it is one, and that is what this does. + /// + /// + /// Undetermined is not a verdict. An undeclared variable, or a node the check does + /// not read, gives , never a guess. + /// + /// + public static class Dimensions + { + /// + /// The dimension of as written, or the subexpression where + /// it stops making physical sense. + /// + /// The formula, an expression or a statement. + /// The dimension of each variable it mentions. The constants + /// pi and e and every number are pure numbers and need no entry. + /// + /// with the dimension of the result — a + /// statement such as an equation is a pure number once its sides agree; + /// with the subexpression at fault and why; + /// or where it could not be settled. + /// + /// + /// + /// A literal 0 or oo fits any dimension where it is added or compared, + /// since it is the same quantity in every unit: v = 0 is meaningful. + /// + /// + /// Nothing is simplified first. sin(x) - sin(x) with x a length is + /// inconsistent, although it simplifies to 0. + /// + /// + /// + /// + /// using System; + /// using System.Collections.Generic; + /// using AngouriMath; + /// using AngouriMath.Core; + /// + /// var acceleration = Dimension.Length / Dimension.Time.Pow(2); + /// var dims = new Dictionary<Entity.Variable, Dimension> + /// { + /// ["g"] = acceleration, ["h"] = Dimension.Length, ["t"] = Dimension.Time, + /// }; + /// Console.WriteLine(MathS.Dimensions.Of("sqrt(2 g h)", dims)); + /// Console.WriteLine(MathS.Dimensions.Of("h - g t^2 / 2 = 0", dims)); + /// Console.WriteLine(MathS.Dimensions.Of("h + g t", dims)); + /// + /// Prints + /// + /// Consistent: L T^-1 + /// Consistent: 1 + /// Inconsistent at h + g * t: h has dimension L and g * t has dimension L T^-1, so they cannot be added + /// + /// + public static DimensionCheck Of(Entity expr, IReadOnlyDictionary dimensions) + => DimensionAnalysis.Of(expr, dimensions); + + /// + /// A basis of the dimensionless products of powers of : + /// the Buckingham π groups. + /// + /// + /// The variables of the problem, each declared in . + /// Their order chooses the basis: the earlier ones are the repeating variables, and + /// each later variable appears to the first power in exactly one group. + /// + /// The dimension of each variable. + /// + /// One group per variable beyond the rank of the dimension matrix, each written with + /// the smallest whole powers and each checked to be a pure number before it is + /// returned. An empty list means no product of these variables is dimensionless. + /// + /// + /// A model whose output depends on these variables depends on them only through + /// the groups, which is what makes a scale model of a ship mean anything, and what + /// reduces the parameters a simulation has to be tuned over. + /// + /// + /// + /// using System; + /// using System.Collections.Generic; + /// using AngouriMath; + /// using AngouriMath.Core; + /// + /// // Flow in a pipe: density, speed, diameter, viscosity. + /// var dims = new Dictionary<Entity.Variable, Dimension> + /// { + /// ["rho"] = Dimension.Mass / Dimension.Length.Pow(3), + /// ["v"] = Dimension.Length / Dimension.Time, + /// ["d"] = Dimension.Length, + /// ["mu"] = Dimension.Mass / (Dimension.Length * Dimension.Time), + /// }; + /// foreach (var group in MathS.Dimensions.DimensionlessGroups(new Entity.Variable[] { "rho", "v", "d", "mu" }, dims)) + /// Console.WriteLine(group); + /// + /// Prints + /// + /// mu / (rho * v * d) + /// + /// + public static IReadOnlyList DimensionlessGroups(IReadOnlyList variables, IReadOnlyDictionary dimensions) + => AngouriMath.Functions.DimensionlessGroups.Of(variables, dimensions); + } + } +} diff --git a/Sources/AngouriMath/Functions/Dimensions/Dimension.cs b/Sources/AngouriMath/Functions/Dimensions/Dimension.cs new file mode 100644 index 000000000..2a4215be1 --- /dev/null +++ b/Sources/AngouriMath/Functions/Dimensions/Dimension.cs @@ -0,0 +1,174 @@ +// +// 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 PeterO.Numbers; + +namespace AngouriMath.Core +{ + /// + /// One of the seven base dimensions of the SI, in the order the SI brochure lists them. + /// + public enum BaseDimension + { + /// L, measured in metres. + Length, + /// M, measured in kilograms. + Mass, + /// T, measured in seconds. + Time, + /// I, measured in amperes. + Current, + /// Θ, measured in kelvins. + Temperature, + /// N, measured in moles. + Amount, + /// J, measured in candelas. + LuminousIntensity, + } + + /// + /// A physical dimension: a product of powers of the seven s, + /// such as L T^-2 for an acceleration. + /// + /// + /// + /// The exponents are rationals, not integers, because a square root of a dimensional + /// quantity is a legitimate intermediate: sqrt(L) appears inside the period of a + /// pendulum before it is divided by sqrt(L T^-2). + /// + /// + /// A dimension says what kind of quantity something is and nothing about its unit: a + /// metre and a foot are both . Units and their conversions are a + /// separate concern, which UnitsNet and its kind already handle. + /// + /// + public sealed class Dimension : IEquatable + { + private const int Count = 7; + [ConstantField] private static readonly string[] symbols = { "L", "M", "T", "I", "Θ", "N", "J" }; + private readonly ERational[] exponents; + + // PeterO keeps a rational as it was computed, 2/2 included; reducing here is what lets + // ToString and IsIntegral read the numerator and denominator directly. + private Dimension(ERational[] exponents) + => this.exponents = exponents.Select(e => + { + var g = e.Numerator.Gcd(e.Denominator); + return g.IsZero || g.Equals(EInteger.One) ? e : ERational.Create(e.Numerator / g, e.Denominator / g); + }).ToArray(); + + private static Dimension Base(BaseDimension b) + { + var exponents = Enumerable.Repeat(ERational.Zero, Count).ToArray(); + exponents[(int)b] = ERational.One; + return new Dimension(exponents); + } + + /// A pure number: a ratio, an angle in radians, a count. + [ConstantField] public static readonly Dimension Dimensionless = new(Enumerable.Repeat(ERational.Zero, Count).ToArray()); + /// L. + [ConstantField] public static readonly Dimension Length = Base(BaseDimension.Length); + /// M. + [ConstantField] public static readonly Dimension Mass = Base(BaseDimension.Mass); + /// T. + [ConstantField] public static readonly Dimension Time = Base(BaseDimension.Time); + /// I. + [ConstantField] public static readonly Dimension Current = Base(BaseDimension.Current); + /// Θ. + [ConstantField] public static readonly Dimension Temperature = Base(BaseDimension.Temperature); + /// N. + [ConstantField] public static readonly Dimension Amount = Base(BaseDimension.Amount); + /// J. + [ConstantField] public static readonly Dimension LuminousIntensity = Base(BaseDimension.LuminousIntensity); + + /// + /// The dimension with the given exponent on each base dimension, in the order of + /// ; unlisted trailing exponents are zero. + /// + /// + /// + /// using System; + /// using AngouriMath.Core; + /// + /// Console.WriteLine(Dimension.Create(1, 1, -2)); + /// + /// Prints + /// + /// L M T^-2 + /// + /// + public static Dimension Create(params int[] exponents) + { + if (exponents.Length > Count) + throw new ArgumentException($"There are {Count} base dimensions, and {exponents.Length} exponents were given.", nameof(exponents)); + var e = Enumerable.Repeat(ERational.Zero, Count).ToArray(); + for (var k = 0; k < exponents.Length; k++) + e[k] = ERational.FromInt32(exponents[k]); + return new Dimension(e); + } + + /// The exponent of . + public Entity.Number.Rational this[BaseDimension b] => Entity.Number.Rational.Create(exponents[(int)b]); + + /// Whether every exponent is zero. + public bool IsDimensionless => exponents.All(e => e.IsZero); + + /// Whether every exponent is a whole number, as a unit system's base units need. + public bool IsIntegral => exponents.All(e => e.Denominator.Equals(EInteger.One)); + + /// The product of two dimensions: exponents add. + public static Dimension operator *(Dimension a, Dimension b) + => new(a.exponents.Zip(b.exponents, (x, y) => x + y).ToArray()); + + /// The quotient of two dimensions: exponents subtract. + public static Dimension operator /(Dimension a, Dimension b) + => new(a.exponents.Zip(b.exponents, (x, y) => x - y).ToArray()); + + /// This dimension to a rational power: every exponent is multiplied by it. + public Dimension Pow(Entity.Number.Rational power) => Pow(power.ERational); + + internal Dimension Pow(ERational power) => new(exponents.Select(e => e * power).ToArray()); + + internal ERational Exponent(int k) => exponents[k]; + + /// + public bool Equals(Dimension? other) + => other is not null && exponents.Zip(other.exponents, (x, y) => x.CompareTo(y) == 0).All(eq => eq); + + /// + public override bool Equals(object? obj) => Equals(obj as Dimension); + + /// + public override int GetHashCode() + => exponents.Aggregate(17, (h, e) => unchecked(h * 31 + e.Numerator.GetHashCode() * 7 + e.Denominator.GetHashCode())); + + /// Equality of every exponent. + public static bool operator ==(Dimension? a, Dimension? b) => a is null ? b is null : a.Equals(b); + + /// Inequality of some exponent. + public static bool operator !=(Dimension? a, Dimension? b) => !(a == b); + + /// + /// The base dimensions with nonzero exponents, in SI order, as L M T^-2; + /// 1 for . + /// + public override string ToString() + { + var parts = new List(); + for (var k = 0; k < Count; k++) + { + var e = exponents[k]; + if (e.IsZero) continue; + parts.Add(e.CompareTo(ERational.One) == 0 ? symbols[k] + : e.Denominator.Equals(EInteger.One) ? $"{symbols[k]}^{e.Numerator}" + : $"{symbols[k]}^({e.Numerator}/{e.Denominator})"); + } + return parts.Count == 0 ? "1" : string.Join(" ", parts); + } + } +} diff --git a/Sources/AngouriMath/Functions/Dimensions/DimensionAnalysis.cs b/Sources/AngouriMath/Functions/Dimensions/DimensionAnalysis.cs new file mode 100644 index 000000000..7d22ba673 --- /dev/null +++ b/Sources/AngouriMath/Functions/Dimensions/DimensionAnalysis.cs @@ -0,0 +1,191 @@ +// +// 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 PeterO.Numbers; +using static AngouriMath.Entity; + +namespace AngouriMath.Functions +{ + /// + /// Reads the dimension off an expression tree, bottom up, given the dimension of each + /// variable. The rules are the ones a physicist checks by eye: a sum and a comparison need + /// their sides to agree, a product multiplies, a power needs a pure-number exponent and, + /// on a dimensional base, a rational one, and a transcendental function needs a pure + /// number to act on. + /// + /// + /// Nothing here simplifies. The check is about the expression as written, so + /// x - x with x a length is a length, and sin(x) - sin(x) with the + /// same x is inconsistent although it simplifies to 0: what was written + /// is meaningless before any rewriting makes it vanish. + /// + internal static class DimensionAnalysis + { + internal static DimensionCheck Of(Entity expr, IReadOnlyDictionary dims) + => expr switch + { + // A constant such as pi or e is a pure number. It is matched before Variable, + // which it derives from. + Constant => DimensionCheck.Ok(Dimension.Dimensionless), + Variable v => dims.TryGetValue(v, out var d) + ? DimensionCheck.Ok(d) + : DimensionCheck.Unknown(v, $"no dimension is declared for {v}"), + Number => DimensionCheck.Ok(Dimension.Dimensionless), + Entity.Boolean => DimensionCheck.Ok(Dimension.Dimensionless), + + Sumf(var a, var b) => Agree(expr, "added", dims, a, b), + Minusf(var a, var b) => Agree(expr, "subtracted", dims, a, b), + Mulf(var a, var b) => Combine(dims, a, b, (x, y) => x * y), + Divf(var a, var b) => Combine(dims, a, b, (x, y) => x / y), + Powf(var b, var p) => Power(expr, dims, b, p), + Modf(var a, var b) => Agree(expr, "taken modulo each other", dims, a, b), + Maxf(var a, var b) => Agree(expr, "compared by max", dims, a, b), + Minf(var a, var b) => Agree(expr, "compared by min", dims, a, b), + + // These keep the dimension of their argument: |3 m| is 3 m. + Absf(var a) => Of(a, dims), + Conjugatef(var a) => Of(a, dims), + Ref(var a) => Of(a, dims), + Imf(var a) => Of(a, dims), + // These read only a direction or a sign, which is a pure number whatever the + // argument measures. + Signumf(var a) => Then(Of(a, dims), _ => DimensionCheck.Ok(Dimension.Dimensionless)), + Argf(var a) => Then(Of(a, dims), _ => DimensionCheck.Ok(Dimension.Dimensionless)), + + Derivativef(var f, Variable v, var n) => Then(Of(f, dims), df => Then(Of(v, dims), dv => + DimensionCheck.Ok(df / dv.Pow(ERational.FromInt32(n))))), + Integralf(var f, Variable v, var range) => Integral(dims, f, v, range), + Limitf(var f, Variable v, var to, _) => Then(Of(v, dims), dv => + Then(Matches(to, dv, dims, "a limit point"), _ => Of(f, dims))), + Summationf(var f, var k, var from, var to) => Index(expr, dims, f, k, from, to, product: false), + Productf(var f, var k, var from, var to) => Index(expr, dims, f, k, from, to, product: true), + Maximumf(var f, _, _) => Of(f, dims), + Minimumf(var f, _, _) => Of(f, dims), + + Providedf(var f, var condition) => Then(Of(condition, dims), _ => Of(f, dims)), + Piecewise pw => Cases(expr, dims, pw), + + ComparisonSign => Agree(expr, "compared", dims, expr.DirectChildren.ToArray()) switch + { + { IsConsistent: true } => DimensionCheck.Ok(Dimension.Dimensionless), + var failed => failed, + }, + // A connective of statements: each must be consistent, and the whole is a truth value. + Statement when expr.DirectChildren.All(c => c is Statement) => AllDimensionless(expr, dims, mustBePure: false), + + // Any other function of numbers is transcendental or combinatorial: sin, log, + // erf, gamma, floor, n!. None of them means anything on a quantity with a + // unit, so each argument has to be a pure number, and so is the result. + CalculusOperator => DimensionCheck.Unknown(expr, $"{expr.GetType().Name} is not read by the dimension check"), + Function => AllDimensionless(expr, dims, mustBePure: true), + + _ => DimensionCheck.Unknown(expr, $"{expr.GetType().Name} is not read by the dimension check"), + }; + + private static DimensionCheck Then(DimensionCheck first, Func next) + => first.IsConsistent ? next(first.Dimension!) : first; + + // Zero and the infinities are the same quantity in every unit, so `v = 0` and + // `x -> +oo` are meaningful whatever v and x measure. Only a literal is exempt: a + // subexpression that happens to vanish is held to what it was written as. + private static bool IsScaleFree(Entity e) + => e is Real r && (r.EDecimal.IsZero || r.EDecimal.IsInfinity()); + + private static DimensionCheck Agree(Entity at, string how, IReadOnlyDictionary dims, params Entity[] operands) + { + Dimension? common = null; + Entity? first = null; + foreach (var operand in operands) + { + var check = Of(operand, dims); + if (!check.IsConsistent) + return check; + if (IsScaleFree(operand)) + continue; + if (common is null) + (common, first) = (check.Dimension, operand); + else if (common != check.Dimension) + return DimensionCheck.Bad(at, $"{first} has dimension {common} and {operand} has dimension {check.Dimension}, so they cannot be {how}"); + } + // Only scale-free literals: 0 + 0 is a pure number. + return DimensionCheck.Ok(common ?? Dimension.Dimensionless); + } + + private static DimensionCheck Matches(Entity e, Dimension expected, IReadOnlyDictionary dims, string what) + => IsScaleFree(e) ? DimensionCheck.Ok(expected) + : Then(Of(e, dims), d => d == expected ? DimensionCheck.Ok(d) + : DimensionCheck.Bad(e, $"{what} has dimension {d} where {expected} is needed")); + + private static DimensionCheck Combine(IReadOnlyDictionary dims, Entity a, Entity b, Func op) + => Then(Of(a, dims), da => Then(Of(b, dims), db => DimensionCheck.Ok(op(da, db)))); + + private static DimensionCheck Power(Entity at, IReadOnlyDictionary dims, Entity b, Entity p) + => Then(Of(b, dims), db => Then(Of(p, dims), dp => + { + if (!dp.IsDimensionless) + return DimensionCheck.Bad(p, $"the exponent {p} has dimension {dp}, and an exponent has to be a pure number"); + if (db.IsDimensionless) + return DimensionCheck.Ok(Dimension.Dimensionless); + // L^q is a dimension only for a rational q: L^pi is not any combination of base units. + var value = p is Number ? p : p.Vars.Any() ? null : p.Evaled; + return value switch + { + Rational q => DimensionCheck.Ok(db.Pow(q)), + Number => DimensionCheck.Bad(at, $"{b} has dimension {db} and is raised to {p}, which is not rational"), + _ => DimensionCheck.Unknown(at, $"{b} has dimension {db} and is raised to {p}, whose value is not known"), + }; + })); + + private static DimensionCheck Integral(IReadOnlyDictionary dims, Entity f, Variable v, (Entity from, Entity to)? range) + => Then(Of(f, dims), df => Then(Of(v, dims), dv => + range is var (from, to) + ? Then(Matches(from, dv, dims, "a lower bound"), _ => Then(Matches(to, dv, dims, "an upper bound"), + _ => DimensionCheck.Ok(df * dv))) + : DimensionCheck.Ok(df * dv))); + + // The index of a sum or product counts terms, so it is a pure number unless declared + // otherwise; a product of n terms of dimension D is D^n, which is a dimension only + // when n is a known number, and is left undetermined rather than guessed otherwise. + private static DimensionCheck Index(Entity at, IReadOnlyDictionary dims, Entity f, Entity k, Entity from, Entity to, bool product) + { + var extended = dims; + if (k is Variable kv && !dims.ContainsKey(kv)) + extended = new Dictionary(dims.ToDictionary(p => p.Key, p => p.Value)) { [kv] = Dimension.Dimensionless }; + return Then(Of(k, extended), dk => !dk.IsDimensionless + ? DimensionCheck.Bad(k, $"the index {k} has dimension {dk}, and an index counts terms") + : Then(Matches(from, dk, extended, "a bound of the index"), _ => Then(Matches(to, dk, extended, "a bound of the index"), + _ => Then(Of(f, extended), df => !product || df.IsDimensionless + ? DimensionCheck.Ok(df) + : DimensionCheck.Unknown(at, $"a product of terms of dimension {df} has that dimension to the number of terms"))))); + } + + private static DimensionCheck Cases(Entity at, IReadOnlyDictionary dims, Piecewise pw) + { + foreach (var c in pw.Cases) + { + var condition = Of(c.Predicate, dims); + if (!condition.IsConsistent) + return condition; + } + return Agree(at, "cases of one piecewise", dims, pw.Cases.Select(c => c.Expression).ToArray()); + } + + private static DimensionCheck AllDimensionless(Entity at, IReadOnlyDictionary dims, bool mustBePure) + { + foreach (var child in at.DirectChildren) + { + var check = Of(child, dims); + if (!check.IsConsistent) + return check; + if (mustBePure && !check.Dimension!.IsDimensionless) + return DimensionCheck.Bad(at, $"{child} has dimension {check.Dimension}, and {at.GetType().Name.TrimEnd('f')} only takes a pure number"); + } + return DimensionCheck.Ok(Dimension.Dimensionless); + } + } +} diff --git a/Sources/AngouriMath/Functions/Dimensions/DimensionCheck.cs b/Sources/AngouriMath/Functions/Dimensions/DimensionCheck.cs new file mode 100644 index 000000000..11eec12d1 --- /dev/null +++ b/Sources/AngouriMath/Functions/Dimensions/DimensionCheck.cs @@ -0,0 +1,64 @@ +// +// 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. +// + +namespace AngouriMath.Core +{ + /// What a dimensional check settled. + public enum DimensionStatus + { + /// Every part of the expression has a dimension and they fit together. + Consistent, + /// + /// Some part of the expression is physically meaningless: two different dimensions are + /// added or compared, or a dimensional quantity is passed to a function such as + /// sin that only takes a pure number. + /// + Inconsistent, + /// + /// The check could not settle it — a variable has no declared dimension, or a node is + /// not one the check reads. This is not a verdict that the expression is wrong. + /// + Undetermined, + } + + /// + /// The outcome of : a status, the dimension where it is + /// , and where it is not, the smallest subexpression + /// at fault and why. + /// + /// What was settled. + /// + /// The dimension of the whole expression; unless + /// is . A statement — an + /// equation, an inequality, a conjunction — is , + /// being a truth value, once both sides of every comparison in it agree. + /// + /// + /// The subexpression the verdict is about: the first inconsistent or undeterminable one in + /// evaluation order. when is + /// . + /// + /// Why, in a sentence, naming the dimensions involved. + public sealed record DimensionCheck(DimensionStatus Status, Dimension? Dimension, Entity? At, string Reason) + { + internal static DimensionCheck Ok(Dimension d) => new(DimensionStatus.Consistent, d, null, ""); + + internal static DimensionCheck Bad(Entity at, string reason) => new(DimensionStatus.Inconsistent, null, at, reason); + + internal static DimensionCheck Unknown(Entity at, string reason) => new(DimensionStatus.Undetermined, null, at, reason); + + /// Whether this is . + public bool IsConsistent => Status == DimensionStatus.Consistent; + + /// + public override string ToString() => Status switch + { + DimensionStatus.Consistent => $"Consistent: {Dimension}", + _ => $"{Status} at {At}: {Reason}", + }; + } +} diff --git a/Sources/AngouriMath/Functions/Dimensions/DimensionlessGroups.cs b/Sources/AngouriMath/Functions/Dimensions/DimensionlessGroups.cs new file mode 100644 index 000000000..e0a1eb9c0 --- /dev/null +++ b/Sources/AngouriMath/Functions/Dimensions/DimensionlessGroups.cs @@ -0,0 +1,112 @@ +// +// 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 AngouriMath.Core.Exceptions; +using PeterO.Numbers; +using static AngouriMath.Entity; + +namespace AngouriMath.Functions +{ + /// + /// The Buckingham π theorem made constructive: the products of powers of the given + /// variables that are pure numbers form a lattice, and a basis of it is read off the + /// null space of the dimension matrix. + /// + /// + /// Row reduction pivots on the leftmost columns it can, so the variables listed first are + /// the ones that recur across the groups and each later one appears, to the first power, + /// in exactly one group. That is how a physicist chooses "repeating variables", and the + /// order of the list is how a caller chooses them here. + /// + internal static class DimensionlessGroups + { + internal static IReadOnlyList Of(IReadOnlyList variables, IReadOnlyDictionary dims) + { + var n = variables.Count; + var missing = variables.FirstOrDefault(v => !dims.ContainsKey(v)); + if (missing is not null) + throw new ArgumentException($"No dimension is declared for {missing}.", nameof(dims)); + if (variables.Distinct().Count() != n) + throw new ArgumentException("A variable is listed twice.", nameof(variables)); + + const int rows = 7; + var m = new ERational[rows, n]; + for (var r = 0; r < rows; r++) + for (var c = 0; c < n; c++) + m[r, c] = dims[variables[c]].Exponent(r); + + // Reduced row echelon form, exactly. + var pivotOfRow = new List(); + var row = 0; + for (var col = 0; col < n && row < rows; col++) + { + var p = row; + while (p < rows && m[p, col].IsZero) + p++; + if (p == rows) + continue; + for (var c = 0; c < n; c++) + (m[row, c], m[p, c]) = (m[p, c], m[row, c]); + var lead = m[row, col]; + for (var c = 0; c < n; c++) + m[row, c] /= lead; + for (var r = 0; r < rows; r++) + { + if (r == row || m[r, col].IsZero) + continue; + var factor = m[r, col]; + for (var c = 0; c < n; c++) + m[r, c] -= factor * m[row, c]; + } + pivotOfRow.Add(col); + row++; + } + + var groups = new List(); + foreach (var free in Enumerable.Range(0, n).Except(pivotOfRow)) + { + var x = Enumerable.Repeat(ERational.Zero, n).ToArray(); + x[free] = ERational.One; + for (var r = 0; r < pivotOfRow.Count; r++) + x[pivotOfRow[r]] = -m[r, free]; + + // Clear denominators and common factors, so that the group reads with the + // smallest whole powers: rho v L / mu rather than sqrt of its square. + var lcm = x.Aggregate(EInteger.One, (acc, q) => acc * q.Denominator / acc.Gcd(q.Denominator)); + var ints = x.Select(q => q.Numerator * (lcm / q.Denominator)).ToArray(); + var gcd = ints.Aggregate(EInteger.Zero, (acc, k) => acc.Gcd(k.Abs())); + ints = ints.Select(k => k / gcd).ToArray(); + + var group = Product(variables, ints); + var check = DimensionAnalysis.Of(group, dims); + if (!check.IsConsistent || !check.Dimension!.IsDimensionless) + throw new AngouriBugException($"The dimensionless group {group} has dimension {check}"); + groups.Add(group); + } + return groups; + } + + private static Entity Product(IReadOnlyList variables, EInteger[] powers) + { + static Entity Factor(Variable v, EInteger k) => k.Equals(EInteger.One) ? v : new Powf(v, Integer.Create(k)); + Entity? Side(Func which, Func magnitude) + => variables.Zip(powers, (v, k) => (v, k)).Where(t => which(t.k)) + .Select(t => Factor(t.v, magnitude(t.k))) + .Aggregate((Entity?)null, (acc, f) => acc is null ? f : new Mulf(acc, f)); + var numerator = Side(k => k.Sign > 0, k => k); + var denominator = Side(k => k.Sign < 0, k => -k); + return (numerator, denominator) switch + { + (null, null) => Integer.One, + (var num, null) => num, + (null, var den) => new Divf(Integer.One, den), + (var num, var den) => new Divf(num, den), + }; + } + } +} diff --git a/Sources/Tests/UnitTests/Common/PublicApi.txt b/Sources/Tests/UnitTests/Common/PublicApi.txt index 6efa8c7ec..0d2b7db93 100644 --- a/Sources/Tests/UnitTests/Common/PublicApi.txt +++ b/Sources/Tests/UnitTests/Common/PublicApi.txt @@ -11,6 +11,14 @@ AngouriMath.Core.ApproachFrom.BothSides : AngouriMath.Core.ApproachFrom AngouriMath.Core.ApproachFrom.Left : AngouriMath.Core.ApproachFrom AngouriMath.Core.ApproachFrom.Right : AngouriMath.Core.ApproachFrom AngouriMath.Core.ApproachFrom.value__ : System.Int32 +AngouriMath.Core.BaseDimension.Amount : AngouriMath.Core.BaseDimension +AngouriMath.Core.BaseDimension.Current : AngouriMath.Core.BaseDimension +AngouriMath.Core.BaseDimension.Length : AngouriMath.Core.BaseDimension +AngouriMath.Core.BaseDimension.LuminousIntensity : AngouriMath.Core.BaseDimension +AngouriMath.Core.BaseDimension.Mass : AngouriMath.Core.BaseDimension +AngouriMath.Core.BaseDimension.Temperature : AngouriMath.Core.BaseDimension +AngouriMath.Core.BaseDimension.Time : AngouriMath.Core.BaseDimension +AngouriMath.Core.BaseDimension.value__ : System.Int32 AngouriMath.Core.Budgets.BudgetOutcome.$() : AngouriMath.Core.Budgets.BudgetOutcome AngouriMath.Core.Budgets.BudgetOutcome.Completed { } : System.Boolean AngouriMath.Core.Budgets.BudgetOutcome.Deconstruct(System.String&, System.String&, System.Int64&, System.TimeSpan&, System.Boolean&) : System.Void @@ -179,6 +187,45 @@ AngouriMath.Core.CostModel.ToString() : System.String AngouriMath.Core.CostModel.ctor(System.String, System.String, System.Func) AngouriMath.Core.CostModel.op_Equality(AngouriMath.Core.CostModel, AngouriMath.Core.CostModel) : System.Boolean AngouriMath.Core.CostModel.op_Inequality(AngouriMath.Core.CostModel, AngouriMath.Core.CostModel) : System.Boolean +AngouriMath.Core.Dimension.Amount : AngouriMath.Core.Dimension +AngouriMath.Core.Dimension.Create(System.Int32[]) : AngouriMath.Core.Dimension +AngouriMath.Core.Dimension.Current : AngouriMath.Core.Dimension +AngouriMath.Core.Dimension.Dimensionless : AngouriMath.Core.Dimension +AngouriMath.Core.Dimension.Equals(AngouriMath.Core.Dimension) : System.Boolean +AngouriMath.Core.Dimension.Equals(System.Object) : System.Boolean +AngouriMath.Core.Dimension.GetHashCode() : System.Int32 +AngouriMath.Core.Dimension.IsDimensionless { } : System.Boolean +AngouriMath.Core.Dimension.IsIntegral { } : System.Boolean +AngouriMath.Core.Dimension.Item { } : AngouriMath.Entity+Number+Rational +AngouriMath.Core.Dimension.Length : AngouriMath.Core.Dimension +AngouriMath.Core.Dimension.LuminousIntensity : AngouriMath.Core.Dimension +AngouriMath.Core.Dimension.Mass : AngouriMath.Core.Dimension +AngouriMath.Core.Dimension.Pow(AngouriMath.Entity+Number+Rational) : AngouriMath.Core.Dimension +AngouriMath.Core.Dimension.Temperature : AngouriMath.Core.Dimension +AngouriMath.Core.Dimension.Time : AngouriMath.Core.Dimension +AngouriMath.Core.Dimension.ToString() : System.String +AngouriMath.Core.Dimension.op_Division(AngouriMath.Core.Dimension, AngouriMath.Core.Dimension) : AngouriMath.Core.Dimension +AngouriMath.Core.Dimension.op_Equality(AngouriMath.Core.Dimension, AngouriMath.Core.Dimension) : System.Boolean +AngouriMath.Core.Dimension.op_Inequality(AngouriMath.Core.Dimension, AngouriMath.Core.Dimension) : System.Boolean +AngouriMath.Core.Dimension.op_Multiply(AngouriMath.Core.Dimension, AngouriMath.Core.Dimension) : AngouriMath.Core.Dimension +AngouriMath.Core.DimensionCheck.$() : AngouriMath.Core.DimensionCheck +AngouriMath.Core.DimensionCheck.At { } : AngouriMath.Entity +AngouriMath.Core.DimensionCheck.Deconstruct(AngouriMath.Core.DimensionStatus&, AngouriMath.Core.Dimension&, AngouriMath.Entity&, System.String&) : System.Void +AngouriMath.Core.DimensionCheck.Dimension { } : AngouriMath.Core.Dimension +AngouriMath.Core.DimensionCheck.Equals(AngouriMath.Core.DimensionCheck) : System.Boolean +AngouriMath.Core.DimensionCheck.Equals(System.Object) : System.Boolean +AngouriMath.Core.DimensionCheck.GetHashCode() : System.Int32 +AngouriMath.Core.DimensionCheck.IsConsistent { } : System.Boolean +AngouriMath.Core.DimensionCheck.Reason { } : System.String +AngouriMath.Core.DimensionCheck.Status { } : AngouriMath.Core.DimensionStatus +AngouriMath.Core.DimensionCheck.ToString() : System.String +AngouriMath.Core.DimensionCheck.ctor(AngouriMath.Core.DimensionStatus, AngouriMath.Core.Dimension, AngouriMath.Entity, System.String) +AngouriMath.Core.DimensionCheck.op_Equality(AngouriMath.Core.DimensionCheck, AngouriMath.Core.DimensionCheck) : System.Boolean +AngouriMath.Core.DimensionCheck.op_Inequality(AngouriMath.Core.DimensionCheck, AngouriMath.Core.DimensionCheck) : System.Boolean +AngouriMath.Core.DimensionStatus.Consistent : AngouriMath.Core.DimensionStatus +AngouriMath.Core.DimensionStatus.Inconsistent : AngouriMath.Core.DimensionStatus +AngouriMath.Core.DimensionStatus.Undetermined : AngouriMath.Core.DimensionStatus +AngouriMath.Core.DimensionStatus.value__ : System.Int32 AngouriMath.Core.Domain.Any : AngouriMath.Core.Domain AngouriMath.Core.Domain.Boolean : AngouriMath.Core.Domain AngouriMath.Core.Domain.Complex : AngouriMath.Core.Domain @@ -3702,6 +3749,8 @@ AngouriMath.MathS+DecimalConst.eulergamma { } : PeterO.Numbers.EDecimal AngouriMath.MathS+DecimalConst.pi { } : PeterO.Numbers.EDecimal AngouriMath.MathS+Diagnostic.CatchOnSimplify { } : AngouriMath.Convenience.Setting> AngouriMath.MathS+Diagnostic.OutputExplicit { } : AngouriMath.Convenience.Setting +AngouriMath.MathS+Dimensions.DimensionlessGroups(System.Collections.Generic.IReadOnlyList, System.Collections.Generic.IReadOnlyDictionary) : System.Collections.Generic.IReadOnlyList +AngouriMath.MathS+Dimensions.Of(AngouriMath.Entity, System.Collections.Generic.IReadOnlyDictionary) : AngouriMath.Core.DimensionCheck AngouriMath.MathS+ExperimentalFeatures.DecomposeRational(AngouriMath.Entity+Number+Integer, AngouriMath.Entity+Number+Integer) : System.Collections.Generic.IEnumerable> AngouriMath.MathS+ExperimentalFeatures.DecomposeRational(AngouriMath.Entity+Number+Rational) : System.Collections.Generic.IEnumerable> AngouriMath.MathS+ExperimentalFeatures.ExpandCosineArgumentMultiplied(AngouriMath.Entity, AngouriMath.Entity, System.Int32) : AngouriMath.Entity @@ -4013,6 +4062,8 @@ class AngouriMath.Core.Budgets.WorkBudget class AngouriMath.Core.Compilation.IntoLinq.CompilationProtocol class AngouriMath.Core.Compilation.IntoLinq.TensorCompilation class AngouriMath.Core.CostModel +class AngouriMath.Core.Dimension +class AngouriMath.Core.DimensionCheck class AngouriMath.Core.EquationSystem class AngouriMath.Core.Exceptions.AngouriBugException class AngouriMath.Core.Exceptions.AngouriMathBaseException @@ -4206,6 +4257,7 @@ class AngouriMath.MathS+Compute class AngouriMath.MathS+DecimalConst class AngouriMath.MathS+Diagnostic class AngouriMath.MathS+Diagnostic+DiagnosticCatchException +class AngouriMath.MathS+Dimensions class AngouriMath.MathS+ExperimentalFeatures class AngouriMath.MathS+Hyperbolic class AngouriMath.MathS+Matrices @@ -4224,6 +4276,8 @@ class AngouriMath.MathS+Utils class AngouriMath.ProofRecording class AngouriMath.ProofStep enum AngouriMath.Core.ApproachFrom +enum AngouriMath.Core.BaseDimension +enum AngouriMath.Core.DimensionStatus enum AngouriMath.Core.Domain enum AngouriMath.Core.Transformations.EqualityVerdict enum AngouriMath.Core.Transformations.RewriteRuleGrowth diff --git a/Sources/Tests/UnitTests/Convenience/DimensionsTest.cs b/Sources/Tests/UnitTests/Convenience/DimensionsTest.cs new file mode 100644 index 000000000..691ee7afd --- /dev/null +++ b/Sources/Tests/UnitTests/Convenience/DimensionsTest.cs @@ -0,0 +1,155 @@ +// +// 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.Collections.Generic; +using AngouriMath.Core; +using AngouriMath.Extensions; +using Xunit; +using static AngouriMath.Entity; + +namespace AngouriMath.Tests.Convenience +{ + /// + /// : the rules are the textbook ones, so each case is a + /// formula whose verdict a physicist can read off by eye. + /// + [Trait("Area", "Convenience")] + public sealed class DimensionsTest + { + private static readonly Dimension L = Dimension.Length, M = Dimension.Mass, T = Dimension.Time; + + private static readonly Dictionary Mechanics = new() + { + ["h"] = L, ["d"] = L, ["l"] = L, + ["t"] = T, ["tau"] = T, + ["m"] = M, + ["v"] = L / T, + ["g"] = L / T.Pow(2), + ["n"] = Dimension.Dimensionless, + }; + + private static DimensionCheck Check(string expr) => MathS.Dimensions.Of(expr.ToEntity(), Mechanics); + + [Theory] + [InlineData("sqrt(2 g h)", "L T^-1")] + [InlineData("2 pi sqrt(l / g)", "T")] + [InlineData("m g h", "L^2 M T^-2")] + [InlineData("m v^2 / 2", "L^2 M T^-2")] + [InlineData("h / d", "1")] + [InlineData("sin(h / d)", "1")] + [InlineData("e^(-t / tau)", "1")] + [InlineData("ln(h / d)", "1")] + [InlineData("abs(h - d)", "L")] + [InlineData("sign(h)", "1")] + [InlineData("h^(3/2)", "L^(3/2)")] + [InlineData("max(h, d)", "L")] + [InlineData("h + 0", "L")] + [InlineData("derivative(h, t)", "L T^-1")] + [InlineData("integral(v, t)", "L")] + [InlineData("limit(h / t, t, +oo)", "L T^-1")] + [InlineData("h provided t > 0", "L")] + public void AConsistentFormulaHasItsDimension(string expr, string dimension) + { + var check = Check(expr); + Assert.True(check.IsConsistent, check.ToString()); + Assert.Equal(dimension, check.Dimension!.ToString()); + } + + [Theory] + [InlineData("h - g t^2 / 2 = 0")] + [InlineData("v = 0")] + [InlineData("h > d and t < tau")] + [InlineData("v^2 = 2 g h")] + public void AConsistentStatementIsATruthValue(string expr) + { + var check = Check(expr); + Assert.True(check.IsConsistent, check.ToString()); + Assert.True(check.Dimension!.IsDimensionless); + } + + [Theory] + [InlineData("h + g t", "h + g * t")] + [InlineData("v = g h", "v = g * h")] + [InlineData("sin(h)", "sin(h)")] + [InlineData("e^t", "t")] + [InlineData("ln(h)", "ln(h)")] + [InlineData("h^pi", "h ^ pi")] + [InlineData("h provided t > h", "t > h")] + [InlineData("v = g t^2", "v = g * t ^ 2")] + public void AnInconsistentFormulaNamesWhereItBreaks(string expr, string at) + { + var check = Check(expr); + Assert.Equal(DimensionStatus.Inconsistent, check.Status); + Assert.Equal(at, check.At!.ToString()); + } + + // Written, not simplified: the formula is meaningless before it vanishes. + [Fact] + public void NothingIsSimplifiedAway() + => Assert.Equal(DimensionStatus.Inconsistent, Check("sin(h) - sin(h)").Status); + + [Theory] + [InlineData("h + w", "w")] + [InlineData("h^n", "h ^ n")] + public void WhatCannotBeSettledIsNotGuessed(string expr, string at) + { + var check = Check(expr); + Assert.Equal(DimensionStatus.Undetermined, check.Status); + Assert.Equal(at, check.At!.ToString()); + } + + [Fact] + public void APendulumHasOneGroup() + { + var groups = MathS.Dimensions.DimensionlessGroups(new Variable[] { "l", "g", "m", "t" }, Mechanics); + var group = Assert.Single(groups); + Assert.Equal("g * t ^ 2 / l", group.ToString()); + } + + [Fact] + public void PipeFlowHasTheReynoldsNumber() + { + var dims = new Dictionary + { + ["rho"] = M / L.Pow(3), ["v"] = L / T, ["d"] = L, ["mu"] = M / (L * T), + }; + var group = Assert.Single(MathS.Dimensions.DimensionlessGroups(new Variable[] { "rho", "v", "d", "mu" }, dims)); + Assert.Equal("mu / (rho * v * d)", group.ToString()); + } + + [Fact] + public void EveryGroupIsAPureNumber() + { + var vars = new Variable[] { "h", "t", "v", "g", "m", "d", "n" }; + var groups = MathS.Dimensions.DimensionlessGroups(vars, Mechanics); + // Seven variables over a dimension matrix of rank three. + Assert.Equal(4, groups.Count); + foreach (var group in groups) + Assert.True(MathS.Dimensions.Of(group, Mechanics).Dimension!.IsDimensionless, group.ToString()); + } + + [Fact] + public void IndependentDimensionsHaveNoGroup() + => Assert.Empty(MathS.Dimensions.DimensionlessGroups(new Variable[] { "h", "m" }, Mechanics)); + + [Fact] + public void AnUndeclaredVariableIsRefused() + => Assert.Throws(() => MathS.Dimensions.DimensionlessGroups(new Variable[] { "h", "w" }, Mechanics)); + + [Fact] + public void DimensionArithmetic() + { + Assert.Equal("L M T^-2", Dimension.Create(1, 1, -2).ToString()); + Assert.Equal(M * L / T.Pow(2), Dimension.Create(1, 1, -2)); + Assert.Equal("L^(1/2)", L.Pow(Number.Rational.Create(1, 2)).ToString()); + Assert.Equal("1", (L / L).ToString()); + Assert.True((L / L).IsDimensionless); + Assert.False(L.Pow(Number.Rational.Create(1, 2)).IsIntegral); + } + } +} From 61e158e8846bb1f11192d8d86541184cd3681708 Mon Sep 17 00:00:00 2001 From: Rafael Vuijk <133344302+Rafael-SOWNet@users.noreply.github.com> Date: Sun, 1 Nov 2026 01:24:47 +0100 Subject: [PATCH 2/3] Dimensional analysis in the catalogue: dimension and dimensionless_groups AGENTS.md: an operation the library offers by name is an entry of the catalogue. The two queries answer what MathS.Dimensions.Of and DimensionlessGroups answer, which CatalogueTest checks on an input where the two dimension answers differ. No surface offers them yet: the MCP server's Tools.NotOffered and the terminal's OneShot.notOffered list them, pointing at #2298, which proposes am_dimensions. Part of #2292. Co-Authored-By: Claude Opus 5.5 --- .../AngouriMath/Core/Operations/Catalogue.cs | 18 ++++++++++++++++++ Sources/MCP/AngouriMath.Mcp/Tools.cs | 2 ++ .../AngouriMath.Terminal.Lib/OneShot.fs | 3 ++- .../UnitTests/Core/Operations/CatalogueTest.cs | 7 +++++++ 4 files changed, 29 insertions(+), 1 deletion(-) diff --git a/Sources/AngouriMath/Core/Operations/Catalogue.cs b/Sources/AngouriMath/Core/Operations/Catalogue.cs index a5cbcae7a..2e7a799ae 100644 --- a/Sources/AngouriMath/Core/Operations/Catalogue.cs +++ b/Sources/AngouriMath/Core/Operations/Catalogue.cs @@ -280,6 +280,23 @@ internal static class Catalogue "is_prime", "Whether an integer is prime.", static n => n.IsPrime); + // ---------------------------------------------------------------- queries on physical dimensions + + [ConstantField] + private static readonly Parameter TheDimensions = new("dimensions", "The physical dimension of each variable."); + + /// . + public static Query, DimensionCheck>> Dimension { get; } = new( + "dimension", "The physical dimension of an expression from those of its variables, or the part where two dimensions disagree.", + static (e, dimensions) => MathS.Dimensions.Of(e, dimensions), + TheDimensions); + + /// . + public static Query, IReadOnlyDictionary, IReadOnlyList>> DimensionlessGroups { get; } = new( + "dimensionless_groups", "The independent products of powers of variables that have no dimension: their Buckingham pi groups.", + static (variables, dimensions) => MathS.Dimensions.DimensionlessGroups(variables, dimensions), + TheDimensions); + // ---------------------------------------------------------------- the list /// Every entry above, in the order written. @@ -291,6 +308,7 @@ internal static class Catalogue ToBase, FromBase, Determinant, Inverse, Transpose, Rank, ReducedRowEchelonForm, Trace, TensorProduct, PrimeFactorization, Totient, GreatestCommonDivisor, DivisorCount, IsPrime, + Dimension, DimensionlessGroups, ]; /// The entry named , or where there is none. diff --git a/Sources/MCP/AngouriMath.Mcp/Tools.cs b/Sources/MCP/AngouriMath.Mcp/Tools.cs index b376ef79a..a78d8aa04 100644 --- a/Sources/MCP/AngouriMath.Mcp/Tools.cs +++ b/Sources/MCP/AngouriMath.Mcp/Tools.cs @@ -129,6 +129,8 @@ private static JsonObject Schema(JsonObject props, params string[] required) [Catalogue.Glsl.Name] = "waits for am_shader_source, https://github.com/asc-community/AngouriMath/issues/2298", [Catalogue.Normalize.Name] = "am_simplify offers the whole simplification, which starts with this pass", [Catalogue.Evaluate.Name] = "am_evaluate keeps an exact value exact, simplifying rather than evaluating, and adds a numeric value beside it", + [Catalogue.Dimension.Name] = "waits for am_dimensions, https://github.com/asc-community/AngouriMath/issues/2298", + [Catalogue.DimensionlessGroups.Name] = "waits for am_dimensions, https://github.com/asc-community/AngouriMath/issues/2298", }; /// The names of the catalogue's entries, which a test checks the lists above against. diff --git a/Sources/Terminal/AngouriMath.Terminal.Lib/OneShot.fs b/Sources/Terminal/AngouriMath.Terminal.Lib/OneShot.fs index af6866111..3cf75ce73 100644 --- a/Sources/Terminal/AngouriMath.Terminal.Lib/OneShot.fs +++ b/Sources/Terminal/AngouriMath.Terminal.Lib/OneShot.fs @@ -71,7 +71,8 @@ let notOffered = "solve_system_with_parameters"; "solve_conjunction_with_parameters" "alternatives"; "sympy"; "hlsl"; "glsl"; "truth_table"; "satisfying_assignments"; "series"; "to_base"; "from_base" "determinant"; "inverse"; "transpose"; "rank"; "reduced_row_echelon_form"; "trace"; "tensor_product" - "prime_factorization"; "totient"; "greatest_common_divisor"; "divisor_count"; "is_prime"; "are_equal" ] + "prime_factorization"; "totient"; "greatest_common_divisor"; "divisor_count"; "is_prime"; "are_equal" + "dimension"; "dimensionless_groups" ] /// The arguments still to read, falling back to a line of stdin where one is missing or is _. type private Arguments(given: string list, input: TextReader) = diff --git a/Sources/Tests/UnitTests/Core/Operations/CatalogueTest.cs b/Sources/Tests/UnitTests/Core/Operations/CatalogueTest.cs index becd3dfdc..bf2f23876 100644 --- a/Sources/Tests/UnitTests/Core/Operations/CatalogueTest.cs +++ b/Sources/Tests/UnitTests/Core/Operations/CatalogueTest.cs @@ -262,6 +262,13 @@ public void EachEntryAnswersAsTheMethodItNames() Assert.Equal(MathS.NumberTheory.CountDivisors(twelve), Catalogue.DivisorCount.Ask(twelve)); Assert.Equal(twelve.IsPrime, Catalogue.IsPrime.Ask(twelve)); Assert.True(Catalogue.IsPrime.Ask(7)); + + Variable v = "v", t = "t"; + var dimensions = new Dictionary { [x] = Dimension.Length, [v] = Dimension.Length / Dimension.Time, [t] = Dimension.Time }; + Assert.Equal(MathS.Dimensions.Of("x + v t", dimensions), Catalogue.Dimension.Ask("x + v t", dimensions)); + Assert.Equal(MathS.Dimensions.Of("x + v", dimensions), Catalogue.Dimension.Ask("x + v", dimensions)); + Assert.NotEqual(Catalogue.Dimension.Ask("x + v t", dimensions), Catalogue.Dimension.Ask("x + v", dimensions)); + Assert.Equal(MathS.Dimensions.DimensionlessGroups([x, v, t], dimensions), Catalogue.DimensionlessGroups.Ask([x, v, t], dimensions)); } } } From 5e76939326aaeecf73bbdf9b12ae4e98194075aa Mon Sep 17 00:00:00 2001 From: Rafael Vuijk Date: Mon, 16 Nov 2026 12:30:01 +0000 Subject: [PATCH 3/3] Dimensional analysis reads every node type there is, and has a page The walk named no node types added since it was written, and read any Function it did not name as a function of pure numbers: dot, cross, det, trace, transpose, a matrix entry and norm were each taken for transcendental. Every arm now names a concrete node type and the last one reports Undetermined, so a node added later is not read as a pure number by default. DimensionsTest.EveryNodeTypeHasADecidedReading lists the verdict on a sample of every concrete node type and fails, by name, on one it does not list. The new rules: dot and cross multiply dimensions; norm, trace, transpose and a matrix entry keep the entries' dimension; a matrix is read where its entries share one and is undetermined where they do not; det of a written n by n matrix is D^n; partialderivative divides by the slot's dimension; a product over 1..n of dimension D is D^n for written bounds; zeta, beta, the exponential and error integrals, W, polygamma, gcd/lcm and the rest of number theory, the connectives and iverson take pure numbers. A variable ranging over a set (a sum or product over a set, max/min, forall/exists, x in S, argmax, indexed unions) takes the dimension the set's members share; a number set fits a declared variable of any dimension and makes an undeclared one a pure number. A set on its own, lambda and application stay undetermined. Docs/Usage/Dimensions.md has the rules and the issue's examples, the water wave among them; its four samples pass docsamples. A BREAKING entry records the new entry point, as #2470 did for the shaders. Part of #2292. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 1 + BREAKING-CHANGES.md | 19 ++ .../Convenience/MathS.Dimensions.cs | 4 + Sources/AngouriMath/Docs/Usage/Dimensions.md | 170 ++++++++++ .../Functions/Dimensions/DimensionAnalysis.cs | 280 ++++++++++++++--- .../UnitTests/Convenience/DimensionsTest.cs | 294 ++++++++++++++++++ 6 files changed, 722 insertions(+), 46 deletions(-) create mode 100644 Sources/AngouriMath/Docs/Usage/Dimensions.md diff --git a/AGENTS.md b/AGENTS.md index da4b0faa9..5bb525983 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -822,6 +822,7 @@ are short, and a stale one is worse than none — if you change what a file desc | [`Docs/Usage/Syntax.md`](Sources/AngouriMath/Docs/Usage/Syntax.md) | what the parser accepts. The grammar was the only statement of it until [#706](https://github.com/asc-community/AngouriMath/pull/706) | | [`Docs/Usage/Exceptions.md`](Sources/AngouriMath/Docs/Usage/Exceptions.md) | the exception hierarchy under `AngouriMathBaseException` | | [`Docs/Usage/Shaders.md`](Sources/AngouriMath/Docs/Usage/Shaders.md) | `MathS.Shaders.Hlsl` and `Glsl`: a worked example, and where the printed shader and `Compile` differ | +| [`Docs/Usage/Dimensions.md`](Sources/AngouriMath/Docs/Usage/Dimensions.md) | `MathS.Dimensions.Of` and `DimensionlessGroups`: the rule for each kind of node, and a worked example | | [`Docs/Usage/Comparison.md`](Sources/AngouriMath/Docs/Usage/Comparison.md) | how we measure against Math.NET Symbolics, Symbolism and SymPy, with the versions and what each comparison does not establish | | [`Docs/References.md`](Sources/AngouriMath/Docs/References.md) | the books, papers, corpora and reference works the code and its tests draw on, with the link and what each is used for. Add a work there when it is first cited | | [`Docs/Acknowledgements.md`](Sources/AngouriMath/Docs/Acknowledgements.md) and [`Docs/Articles.md`](Sources/AngouriMath/Docs/Articles.md) | the projects AngouriMath is built with, and the maintainers' articles about it, moved from the archived AngouriMathLab | diff --git a/BREAKING-CHANGES.md b/BREAKING-CHANGES.md index 19c580e29..e25d73761 100644 --- a/BREAKING-CHANGES.md +++ b/BREAKING-CHANGES.md @@ -579,6 +579,25 @@ both, and `curl` alone, are still variables ([#2182](https://github.com/asc-comm --- +### Dimensional analysis: `MathS.Dimensions.Of` and `DimensionlessGroups` + +**Not silent: a new entry point.** `MathS.Dimensions.Of(expr, dimensions)` reads a formula against the physical +dimension of each variable, a `Dimension` over the seven SI base dimensions passed in a map, and returns a +`DimensionCheck`: `Consistent` with the dimension of the result, `Inconsistent` with the subexpression where two +dimensions are added or compared or a quantity is passed to a function that takes a pure number, or `Undetermined` +where a variable has no dimension or a node is not read. Nothing is simplified first. `MathS.Dimensions.DimensionlessGroups` +gives the Buckingham π groups of a list of variables. The catalogue has them as `dimension` and `dimensionless_groups`, +not yet offered by the MCP server or the terminal ([#2298](https://github.com/asc-community/AngouriMath/issues/2298)). +Nothing that existed changes. See [`Docs/Usage/Dimensions.md`](Sources/AngouriMath/Docs/Usage/Dimensions.md) +([#2292](https://github.com/asc-community/AngouriMath/issues/2292)). + +| Input, with `g` an acceleration, `h` a length, `t` a time | Was (2.7.0) | Now | +|---|---|---| +| `MathS.Dimensions.Of("sqrt(2 g h)", dims).ToString()` | no such member | `Consistent: L T^-1` | +| `MathS.Dimensions.Of("h + g t", dims).ToString()` | no such member | `Inconsistent at h + g * t: h has dimension L and g * t has dimension L T^-1, so they cannot be added` | +| `MathS.Dimensions.DimensionlessGroups(["h", "g", "t"], dims)` | no such member | `[g * t ^ 2 / h]` | + +--- ### A system row that is not a solution declines the system diff --git a/Sources/AngouriMath/Convenience/MathS.Dimensions.cs b/Sources/AngouriMath/Convenience/MathS.Dimensions.cs index 076ffd3ac..6259a61e1 100644 --- a/Sources/AngouriMath/Convenience/MathS.Dimensions.cs +++ b/Sources/AngouriMath/Convenience/MathS.Dimensions.cs @@ -35,6 +35,10 @@ partial class MathS /// Undetermined is not a verdict. An undeclared variable, or a node the check does /// not read, gives , never a guess. /// + /// + /// The page Docs/Usage/Dimensions.md lists the rule for each kind of node and + /// works the water-wave example through. + /// /// public static class Dimensions { diff --git a/Sources/AngouriMath/Docs/Usage/Dimensions.md b/Sources/AngouriMath/Docs/Usage/Dimensions.md new file mode 100644 index 000000000..997138ee3 --- /dev/null +++ b/Sources/AngouriMath/Docs/Usage/Dimensions.md @@ -0,0 +1,170 @@ +# Dimensional analysis + +`MathS.Dimensions.Of` reads a formula against the physical dimension of each of its variables and +says whether it means anything: the dimension of the result, or the subexpression where two +dimensions are added, compared or passed to a function that only takes a pure number. +`MathS.Dimensions.DimensionlessGroups` gives the Buckingham π groups of a set of variables. + +A dimension is a product of powers of the seven SI base dimensions, `L`, `M`, `T`, `I`, `Θ`, `N` +and `J`, with rational exponents, and is written as `Dimension.Length / Dimension.Time.Pow(2)` or +`Dimension.Create(1, 0, -2)`. It says what kind of quantity something is and nothing about its +unit: checking values in metres and feet is what a units library is for. What a units library +cannot do is look at `sqrt(2 g h)` and say whether it is a speed. + +## Checking a formula + +The dimensions are passed in a map from each variable to its dimension, not attached to the +variables, so the same expression can be read under different assignments and nothing about how +it prints, parses or simplifies changes. A body falling from a height `h`: + +```cs +using System.Collections.Generic; +using AngouriMath.Core; + +var dims = new Dictionary +{ + ["g"] = Dimension.Length / Dimension.Time.Pow(2), + ["h"] = Dimension.Length, + ["t"] = Dimension.Time, +}; +Console.WriteLine(MathS.Dimensions.Of("sqrt(2 g h)", dims)); +Console.WriteLine(MathS.Dimensions.Of("h - g t^2 / 2 = 0", dims)); +Console.WriteLine(MathS.Dimensions.Of("h + g t", dims)); +``` + +Output: + +``` +Consistent: L T^-1 +Consistent: 1 +Inconsistent at h + g * t: h has dimension L and g * t has dimension L T^-1, so they cannot be added +``` + +The answer is a `DimensionCheck`: its `Status` is one of three, its `Dimension` is the dimension of +the result where it is `Consistent`, and `At` and `Reason` say where and why it is not. A statement +such as an equation is a truth value, a pure number written `1`, once the sides of every +comparison in it agree. + +**`Undetermined` is not a verdict.** A variable with no declared dimension, a dimensional quantity +raised to a symbolic power, and a node the check does not read are each reported as undetermined, +with the subexpression, rather than guessed at: + +```cs +using System.Collections.Generic; +using AngouriMath.Core; + +var dims = new Dictionary +{ + ["h"] = Dimension.Length, + ["n"] = Dimension.Dimensionless, +}; +Console.WriteLine(MathS.Dimensions.Of("h + w", dims)); +Console.WriteLine(MathS.Dimensions.Of("h^n", dims)); +``` + +Output: + +``` +Undetermined at w: no dimension is declared for w +Undetermined at h ^ n: h has dimension L and is raised to n, whose value is not known +``` + +## The rules + +**Nothing is simplified first.** The check is about the formula as written: `sin(x) - sin(x)` with +`x` a length is inconsistent, although it simplifies to `0`. + +| | | +|---|---| +| `a + b`, `a - b`, `a mod b`, `max(a, b)`, `min(a, b)`, `a = b`, `a < b` | `a` and `b` have one dimension. A literal `0` or `oo` fits any, so `v = 0` is meaningful | +| `a * b`, `a / b`, `dot(a, b)`, `cross(a, b)` | the dimensions multiply or divide | +| `a ^ p` | `p` is a pure number; where `a` has a dimension, `p` is rational: `L^pi` is no dimension | +| `abs`, `conj`, `re`, `im`, `norm(v, p)`, `trace`, `transpose`, an entry of a matrix | the dimension of the argument | +| `sign`, `arg` | a pure number, whatever the argument measures | +| `sin` and the other trigonometric functions, `exp` and `ln`, the hyperbolic functions, `erf`, `Ei`, `Si`, `Ci`, `li`, `gamma` and `n!`, `beta`, `zeta`, `polygamma`, `lambertw`, `floor`, `ceil`, `round`, the functions of number theory | each argument is a pure number, and so is the value | +| `and`, `or`, `not`, `iverson(P)`, divisibility and congruence | each operand is a truth value or a pure number, and so is the result | +| a matrix or vector | its entries share a dimension, which is the matrix's; a state vector `[x, v]` of mixed dimensions is undetermined | +| `det(A)` of an `n` by `n` matrix | the entries' dimension to the `n`th power, undetermined where `n` is not written | +| `derivative(f, x, n)`, `partialderivative(f, x, n)` | `f`'s dimension over `x`'s to the `n`th power | +| `integral(f, x, a, b)` | `f`'s dimension times `x`'s, with `a` and `b` of `x`'s dimension | +| `limit(f, x, a)` | `f`'s dimension, with `a` of `x`'s | +| `sum(f, k, a, b)`, `product(f, k, a, b)` | the index counts terms and is a pure number unless declared otherwise; a product of `b - a + 1` terms of dimension `D` is `D^(b - a + 1)`, undetermined where that count is not a number | +| `sum(f, x in S)`, `product(f, x in S)`, `max(f, x in S)`, `forall`, `exists`, `x in S` | a variable ranging over `S` takes the dimension `S`'s members share: `x in [0; l]` makes `x` a length. A number set, `RR` or `ZZ`, fits a declared variable of any dimension, since `l in RR` says a length is real, and makes an undeclared one a pure number | +| `f provided P`, a piecewise | `P` is a consistent statement, and the cases share a dimension | +| a set on its own, `lambda`, a function applied | undetermined: none of these is a quantity | + +A node type the check has not been taught is undetermined too, never read as a pure number by +default; a test in the suite lists the verdict on every node type there is and fails on a new one +until someone decides what its dimension is. + +## Buckingham π groups + +A relation between `n` quantities whose dimension matrix has rank `r` can be written as a relation +between `n - r` dimensionless products of them. `DimensionlessGroups` gives a basis of those +products, each with the smallest whole powers, and checks each is a pure number before returning +it. Flow in a pipe, with density, speed, diameter and viscosity, has one, the reciprocal of the +Reynolds number: + +```cs +using System.Collections.Generic; +using AngouriMath.Core; + +var (L, M, T) = (Dimension.Length, Dimension.Mass, Dimension.Time); +var pipe = new Dictionary +{ + ["rho"] = M / L.Pow(3), ["v"] = L / T, ["d"] = L, ["mu"] = M / (L * T), +}; +foreach (var group in MathS.Dimensions.DimensionlessGroups(new Variable[] { "rho", "v", "d", "mu" }, pipe)) + Console.WriteLine(group); +``` + +Output: + +``` +mu / (rho * v * d) +``` + +The order of the variables chooses the basis. The ones listed first recur across the groups, as a +physicist's "repeating variables" do, and each later one appears to the first power in exactly +one group. + +## A worked example: water waves + +The dispersion relation of waves on water of depth `h` is `ω² = g k tanh(k h)`, with `ω` the +angular frequency and `k` the wave number. In deep water `tanh(k h)` is close to `1`, and in +shallow water close to `k h`, which gives the shallow-water speed `ω / k = sqrt(g h)`. Writing +`ω = sqrt(g k h)` for that, a factor of `k` short, is a typical slip, and the check finds it inside +the phase of the wave it is used in: + +```cs +using System.Collections.Generic; +using AngouriMath.Core; + +var (L, T) = (Dimension.Length, Dimension.Time); +var dims = new Dictionary +{ + ["omega"] = Dimension.Dimensionless / T, ["g"] = L / T.Pow(2), ["k"] = Dimension.Dimensionless / L, + ["h"] = L, ["A"] = L, ["x"] = L, ["t"] = T, +}; +Console.WriteLine(MathS.Dimensions.Of("omega^2 = g k tanh(k h)", dims)); +Console.WriteLine(MathS.Dimensions.Of("A sin(k x - omega t)", dims)); +Console.WriteLine(MathS.Dimensions.Of("A sin(k x - sqrt(g k h) t)", dims)); +foreach (var group in MathS.Dimensions.DimensionlessGroups(new Variable[] { "k", "g", "A", "h", "t" }, dims)) + Console.WriteLine(group); +``` + +Output: + +``` +Consistent: 1 +Consistent: L +Inconsistent at k * x - sqrt(g * k * h) * t: k * x has dimension 1 and sqrt(g * k * h) * t has dimension L^(1/2), so they cannot be subtracted +k * A +k * h +k * g * t ^ 2 +``` + +The three groups say that the surface of a wave started from rest depends on the amplitude, the +depth and the time only through `k A`, the steepness, `k h`, the depth in wavelengths, and +`g k t²`, the time in units of the deep-water period. A simulation tuned over those three is tuned +over every wave with the same three values. diff --git a/Sources/AngouriMath/Functions/Dimensions/DimensionAnalysis.cs b/Sources/AngouriMath/Functions/Dimensions/DimensionAnalysis.cs index 7d22ba673..4f96ec83f 100644 --- a/Sources/AngouriMath/Functions/Dimensions/DimensionAnalysis.cs +++ b/Sources/AngouriMath/Functions/Dimensions/DimensionAnalysis.cs @@ -8,6 +8,7 @@ using System; using PeterO.Numbers; using static AngouriMath.Entity; +using static AngouriMath.Entity.Set; namespace AngouriMath.Functions { @@ -19,24 +20,41 @@ namespace AngouriMath.Functions /// number to act on. /// /// + /// /// Nothing here simplifies. The check is about the expression as written, so /// x - x with x a length is a length, and sin(x) - sin(x) with the /// same x is inconsistent although it simplifies to 0: what was written /// is meaningless before any rewriting makes it vanish. + /// + /// + /// Every arm of names a concrete node type, and none matches an abstract + /// one such as or . A node type added to the + /// library later therefore reaches the last arm and is reported + /// , rather than being read as a pure number + /// because it happens to derive from a class whose other members are. + /// DimensionsTest.EveryNodeTypeHasADecidedReading lists the verdict on each node type + /// and fails on one it does not list. + /// + /// + /// A set is not a quantity, so does not give one a dimension. Where a set + /// says what a variable ranges over — x in [0; l], max(f, x in S), a sum over + /// a set — reads the dimension its members share. + /// /// internal static class DimensionAnalysis { internal static DimensionCheck Of(Entity expr, IReadOnlyDictionary dims) => expr switch { - // A constant such as pi or e is a pure number. It is matched before Variable, - // which it derives from. - Constant => DimensionCheck.Ok(Dimension.Dimensionless), + // A constant (pi, e, eulergamma) is a pure number. It is matched before + // Variable, which it derives from. + Constant => Pure, Variable v => dims.TryGetValue(v, out var d) ? DimensionCheck.Ok(d) : DimensionCheck.Unknown(v, $"no dimension is declared for {v}"), - Number => DimensionCheck.Ok(Dimension.Dimensionless), - Entity.Boolean => DimensionCheck.Ok(Dimension.Dimensionless), + // Integer, Rational and Real all derive from Complex. + Number.Complex => Pure, + Entity.Boolean => Pure, Sumf(var a, var b) => Agree(expr, "added", dims, a, b), Minusf(var a, var b) => Agree(expr, "subtracted", dims, a, b), @@ -47,46 +65,106 @@ internal static DimensionCheck Of(Entity expr, IReadOnlyDictionary Agree(expr, "compared by max", dims, a, b), Minf(var a, var b) => Agree(expr, "compared by min", dims, a, b), - // These keep the dimension of their argument: |3 m| is 3 m. + // These keep the dimension of their argument: |3 m| is 3 m, and so are its + // conjugate and its real part. The imaginary part of 3 m + 4i m is 4 m. Absf(var a) => Of(a, dims), Conjugatef(var a) => Of(a, dims), Ref(var a) => Of(a, dims), Imf(var a) => Of(a, dims), // These read only a direction or a sign, which is a pure number whatever the // argument measures. - Signumf(var a) => Then(Of(a, dims), _ => DimensionCheck.Ok(Dimension.Dimensionless)), - Argf(var a) => Then(Of(a, dims), _ => DimensionCheck.Ok(Dimension.Dimensionless)), + Signumf(var a) => Then(Of(a, dims), _ => Pure), + Argf(var a) => Then(Of(a, dims), _ => Pure), - Derivativef(var f, Variable v, var n) => Then(Of(f, dims), df => Then(Of(v, dims), dv => + // A function defined by a series, an integral or a recurrence in its argument + // adds powers of that argument, so the argument has to be a pure number and so + // is the value: sin, ln, erf, the gamma family, zeta, W. Rounding and the + // functions of number theory are defined on numbers, and floor(3.7 m) depends + // on the unit, which is the same failure. A truth value is a pure number too, + // so the connectives and the Iverson bracket are read here. + Sinf or Cosf or Tanf or Cotanf or Secantf or Cosecantf + or Arcsinf or Arccosf or Arctanf or Arccotanf or Arcsecantf or Arccosecantf + or Logf or Eif or Sif or Cif or Shif or Chif or Lif + or Erff or Erfcf or Erfif or LambertWf or Polygammaf or Zetaf or Betaf or IncompleteGammaf + or Factorialf or DoubleFactorialf or Binomialf or FallingFactorialf or RisingFactorialf + or CatalanNumberf or HarmonicNumberf + or Floorf or Ceilf or Roundf + or Gcdf or Lcmf or Phif or Mobiusf or DivisorSigmaf or PrimeNuf or PrimeOmegaf or PrimePif + or Primef or Valuationf or PrimeFactorizationf or Alephf + or Iversonf or Andf or Orf or Notf or Xorf or Impliesf or Dividesf or Congruentf + => AllPure(expr, dims), + + // A count of members is a pure number, whatever the members measure. + Cardf(var s) => Elements(s, dims) switch + { + { Check.Status: DimensionStatus.Inconsistent } and var (check, _) => check, + { Any: true } => Pure, + var (check, _) => Then(check, _ => Pure), + }, + + // A vector or a matrix is read when its entries share a dimension, which is then + // the dimension of the whole: a velocity is [vx, vy] with both a speed. A state + // vector [x, v] mixes a length and a speed, which is meaningful and has no one + // dimension, so it is undetermined rather than inconsistent. + Matrix m => Entries(m, dims), + DotProductf(var a, var b) => Combine(dims, a, b, (x, y) => x * y), + CrossProductf(var a, var b) => Combine(dims, a, b, (x, y) => x * y), + Normf(var a, var p) => Then(MustBePure(expr, p, dims), _ => Of(a, dims)), + Tracef(var a) => Of(a, dims), + Transposef(var a) => Of(a, dims), + MatrixEntryf(var a, var i, var j) => Then(MustBePure(expr, i, dims), _ => Then(MustBePure(expr, j, dims), _ => Of(a, dims))), + Determinantf(var a) => Determinant(expr, dims, a), + + Derivativef(var f, var v, var n) => Then(Of(f, dims), df => Then(Of(v, dims), dv => DimensionCheck.Ok(df / dv.Pow(ERational.FromInt32(n))))), - Integralf(var f, Variable v, var range) => Integral(dims, f, v, range), - Limitf(var f, Variable v, var to, _) => Then(Of(v, dims), dv => + PartialDerivativef(var f, var v, var n) => Then(Of(f, dims), df => Then(Of(v, dims), dv => + DimensionCheck.Ok(df / dv.Pow(ERational.FromInt32(n))))), + Integralf(var f, var v, var range) => Integral(dims, f, v, range), + Limitf(var f, var v, var to, _) => Then(Of(v, dims), dv => Then(Matches(to, dv, dims, "a limit point"), _ => Of(f, dims))), Summationf(var f, var k, var from, var to) => Index(expr, dims, f, k, from, to, product: false), Productf(var f, var k, var from, var to) => Index(expr, dims, f, k, from, to, product: true), - Maximumf(var f, _, _) => Of(f, dims), - Minimumf(var f, _, _) => Of(f, dims), + SumOverSetf(var f, var k, var s) => Bind(expr, dims, k, s, inner => Of(f, inner)), + ProductOverSetf(var f, var k, var s) => Bind(expr, dims, k, s, inner => Then(Of(f, inner), df => + df.IsDimensionless ? Pure + : s is FiniteSet finite ? DimensionCheck.Ok(df.Pow(ERational.FromInt32(finite.Count))) + : DimensionCheck.Unknown(expr, $"a product of terms of dimension {df} has that dimension to the number of terms, and the number of members of {s} is not known"))), + Maximumf(var f, var k, var s) => Bind(expr, dims, k, s, inner => Of(f, inner)), + Minimumf(var f, var k, var s) => Bind(expr, dims, k, s, inner => Of(f, inner)), - Providedf(var f, var condition) => Then(Of(condition, dims), _ => Of(f, dims)), + Providedf(var f, var condition) => Then(MustBePure(expr, condition, dims), _ => Of(f, dims)), Piecewise pw => Cases(expr, dims, pw), - ComparisonSign => Agree(expr, "compared", dims, expr.DirectChildren.ToArray()) switch + Equalsf or Lessf or Greaterf or LessOrEqualf or GreaterOrEqualf + => Then(Agree(expr, "compared", dims, expr.DirectChildren.ToArray()), _ => Pure), + Inf(var x, var s) => Then(Elements(s, dims) switch + { + { Check.Status: DimensionStatus.Inconsistent } and var (check, _) => check, + { Any: true } => Of(x, dims), + var (check, _) => Then(check, ds => Matches(x, ds, dims, $"an element of {s}")), + }, _ => Pure), + Subsetf(var a, var b) => AgreeElements(expr, dims, a, b) switch { - { IsConsistent: true } => DimensionCheck.Ok(Dimension.Dimensionless), - var failed => failed, + { Check.Status: DimensionStatus.Inconsistent } and var (check, _) => check, + { Any: true } => Pure, + var (check, _) => Then(check, _ => Pure), }, - // A connective of statements: each must be consistent, and the whole is a truth value. - Statement when expr.DirectChildren.All(c => c is Statement) => AllDimensionless(expr, dims, mustBePure: false), - - // Any other function of numbers is transcendental or combinatorial: sin, log, - // erf, gamma, floor, n!. None of them means anything on a quantity with a - // unit, so each argument has to be a pure number, and so is the result. - CalculusOperator => DimensionCheck.Unknown(expr, $"{expr.GetType().Name} is not read by the dimension check"), - Function => AllDimensionless(expr, dims, mustBePure: true), + Forallf(var k, var s, var body) => Bind(expr, dims, k, s, inner => MustBePure(expr, body, inner)), + Existsf(var k, var s, var body) => Bind(expr, dims, k, s, inner => MustBePure(expr, body, inner)), + ExistsUniquef(var k, var s, var body) => Bind(expr, dims, k, s, inner => MustBePure(expr, body, inner)), - _ => DimensionCheck.Unknown(expr, $"{expr.GetType().Name} is not read by the dimension check"), + // A set, argmax and argmin among them, is not a quantity. Where one says what a + // variable ranges over, Elements reads it. Lambda and Application are functions + // and their applications, whose dimensions nothing declares. Anything else is a + // node this check has not been taught, and is not guessed at. + _ => NotRead(expr), }; + [ConstantField] private static readonly DimensionCheck Pure = DimensionCheck.Ok(Dimension.Dimensionless); + + private static DimensionCheck NotRead(Entity expr) + => DimensionCheck.Unknown(expr, $"{expr.GetType().Name} is not read by the dimension check"); + private static DimensionCheck Then(DimensionCheck first, Func next) => first.IsConsistent ? next(first.Dimension!) : first; @@ -97,6 +175,11 @@ private static bool IsScaleFree(Entity e) => e is Real r && (r.EDecimal.IsZero || r.EDecimal.IsInfinity()); private static DimensionCheck Agree(Entity at, string how, IReadOnlyDictionary dims, params Entity[] operands) + => AgreeOrAny(at, how, dims, operands).Check; + + // Any is set where every operand was a scale-free literal: 0 + 0 is a pure number, and + // the interval [0; +oo) is one whose members can measure anything. + private static (DimensionCheck Check, bool Any) AgreeOrAny(Entity at, string how, IReadOnlyDictionary dims, IEnumerable operands) { Dimension? common = null; Entity? first = null; @@ -104,16 +187,15 @@ private static DimensionCheck Agree(Entity at, string how, IReadOnlyDictionary dims, string what) @@ -121,6 +203,12 @@ private static DimensionCheck Matches(Entity e, Dimension expected, IReadOnlyDic : Then(Of(e, dims), d => d == expected ? DimensionCheck.Ok(d) : DimensionCheck.Bad(e, $"{what} has dimension {d} where {expected} is needed")); + private static DimensionCheck MustBePure(Entity at, Entity operand, IReadOnlyDictionary dims) + => Then(Of(operand, dims), d => d.IsDimensionless ? Pure + : DimensionCheck.Bad(at, $"{operand} has dimension {d}, and {Name(at)} only takes a pure number there")); + + private static string Name(Entity at) => at.GetType().Name.TrimEnd('f'); + private static DimensionCheck Combine(IReadOnlyDictionary dims, Entity a, Entity b, Func op) => Then(Of(a, dims), da => Then(Of(b, dims), db => DimensionCheck.Ok(op(da, db)))); @@ -130,7 +218,7 @@ private static DimensionCheck Power(Entity at, IReadOnlyDictionary dims, Entity f, Variable v, (Entity from, Entity to)? range) + private static DimensionCheck Integral(IReadOnlyDictionary dims, Entity f, Entity v, (Entity from, Entity to)? range) => Then(Of(f, dims), df => Then(Of(v, dims), dv => range is var (from, to) ? Then(Matches(from, dv, dims, "a lower bound"), _ => Then(Matches(to, dv, dims, "an upper bound"), @@ -149,43 +237,143 @@ range is var (from, to) : DimensionCheck.Ok(df * dv))); // The index of a sum or product counts terms, so it is a pure number unless declared - // otherwise; a product of n terms of dimension D is D^n, which is a dimension only - // when n is a known number, and is left undetermined rather than guessed otherwise. + // otherwise. A product of n terms of dimension D is D^n, which is a dimension only when + // n is a known number, and is left undetermined rather than guessed otherwise. private static DimensionCheck Index(Entity at, IReadOnlyDictionary dims, Entity f, Entity k, Entity from, Entity to, bool product) { - var extended = dims; - if (k is Variable kv && !dims.ContainsKey(kv)) - extended = new Dictionary(dims.ToDictionary(p => p.Key, p => p.Value)) { [kv] = Dimension.Dimensionless }; + var extended = k is Variable kv && !dims.ContainsKey(kv) ? With(dims, kv, Dimension.Dimensionless) : dims; return Then(Of(k, extended), dk => !dk.IsDimensionless ? DimensionCheck.Bad(k, $"the index {k} has dimension {dk}, and an index counts terms") : Then(Matches(from, dk, extended, "a bound of the index"), _ => Then(Matches(to, dk, extended, "a bound of the index"), - _ => Then(Of(f, extended), df => !product || df.IsDimensionless - ? DimensionCheck.Ok(df) - : DimensionCheck.Unknown(at, $"a product of terms of dimension {df} has that dimension to the number of terms"))))); + _ => Then(Of(f, extended), df => + !product || df.IsDimensionless ? DimensionCheck.Ok(df) + : (from, to) is (Integer a, Integer b) + ? DimensionCheck.Ok(df.Pow(ERational.FromEInteger(EInteger.Max(b.EInteger - a.EInteger + 1, EInteger.Zero)))) + : DimensionCheck.Unknown(at, $"a product of terms of dimension {df} has that dimension to the number of terms, and {to} - {from} + 1 is not a known number"))))); + } + + // A variable bound to range over a set takes the dimension the set's members share. One + // declared by the caller has to agree with it; one not declared is given it, for the + // body only. + private static DimensionCheck Bind(Entity at, IReadOnlyDictionary dims, Entity k, Entity s, Func, DimensionCheck> body) + { + if (k is not Variable kv) + return NotRead(at); + var (members, any) = Elements(s, dims); + if (members.Status is DimensionStatus.Inconsistent) + return members; + if (dims.TryGetValue(kv, out var declared)) + return any ? body(dims) + : !members.IsConsistent ? members + : declared == members.Dimension ? body(dims) + : DimensionCheck.Bad(at, $"{kv} has dimension {declared} and ranges over {s}, whose members have dimension {members.Dimension}"); + return members.IsConsistent ? body(With(dims, kv, members.Dimension!)) : members; + } + + private static IReadOnlyDictionary With(IReadOnlyDictionary dims, Variable v, Dimension d) + => new Dictionary(dims.ToDictionary(p => p.Key, p => p.Value)) { [v] = d }; + + /// + /// What the members of a set measure. Check is the dimension a variable ranging + /// over the set takes when the caller declared none for it. Any is set where the + /// set allows a declared variable of any dimension: [0; +oo), whose ends are the + /// same in every unit, and the number sets, since l in RR is how a length is said + /// to be real. A variable nobody declared that ranges over a number set is a pure + /// number, as the index of a sum is; one ranging over [0; +oo) is undetermined. + /// + internal static (DimensionCheck Check, bool Any) Elements(Entity s, IReadOnlyDictionary dims) + => s switch + { + SpecialSet.Integers or SpecialSet.Rationals or SpecialSet.Reals or SpecialSet.Complexes + or SpecialSet.NonNegativeIntegers or SpecialSet.PositiveIntegers or SpecialSet.Primes or SpecialSet.Booleans + => (Pure, true), + FiniteSet { Count: 0 } => (DimensionCheck.Unknown(s, "the empty set has no members to read a dimension from"), true), + FiniteSet finite => ScaleFree(s, AgreeOrAny(s, "members of one set", dims, finite)), + Interval(var left, _, var right, _) => ScaleFree(s, AgreeOrAny(s, "ends of one interval", dims, new[] { left, right })), + Unionf(var a, var b) => AgreeElements(s, dims, a, b), + Intersectionf(var a, var b) => AgreeElements(s, dims, a, b), + SetMinusf(var a, var b) => AgreeElements(s, dims, a, b), + // The prime factors of a number are numbers, and only of a number. + PrimeFactorsf(var n) => (MustBePure(s, n, dims), false), + // { x | P(x) } has members of x's dimension, once P is a consistent statement. + ConditionalSet(var x, var predicate) => (Then(Of(x, dims), dx => Then(MustBePure(s, predicate, dims), _ => DimensionCheck.Ok(dx))), false), + // The points where f is largest are values of the variable. + Argmaxf(var f, var k, var over) => (Bind(s, dims, k, over, inner => Then(Of(f, inner), _ => Of(k, inner))), false), + Argminf(var f, var k, var over) => (Bind(s, dims, k, over, inner => Then(Of(f, inner), _ => Of(k, inner))), false), + IndexedUnionf(var k, var over, var body) => (Bind(s, dims, k, over, inner => Elements(body, inner).Check), false), + IndexedIntersectionf(var k, var over, var body) => (Bind(s, dims, k, over, inner => Elements(body, inner).Check), false), + // A variable standing for a set, a power set, whose members are sets, and + // anything not listed: not read. + _ => (NotRead(s), false), + }; + + private static (DimensionCheck Check, bool Any) ScaleFree(Entity s, (DimensionCheck Check, bool Any) read) + => read.Any ? (DimensionCheck.Unknown(s, $"the members of {s} can measure anything"), true) : read; + + private static (DimensionCheck Check, bool Any) AgreeElements(Entity at, IReadOnlyDictionary dims, Entity a, Entity b) + { + var (ca, anyA) = Elements(a, dims); + if (ca.Status is DimensionStatus.Inconsistent) return (ca, false); + var (cb, anyB) = Elements(b, dims); + if (cb.Status is DimensionStatus.Inconsistent) return (cb, false); + if (anyA && anyB) return (ca.IsConsistent ? ca : cb, true); + if (anyA) return (cb, false); + if (anyB) return (ca, false); + if (!ca.IsConsistent) return (ca, false); + if (!cb.IsConsistent) return (cb, false); + return ca.Dimension == cb.Dimension ? (ca, false) + : (DimensionCheck.Bad(at, $"the members of {a} have dimension {ca.Dimension} and those of {b} have dimension {cb.Dimension}"), false); } + private static DimensionCheck Entries(Matrix m, IReadOnlyDictionary dims) + { + Dimension? common = null; + // The entries themselves: enumerating a matrix gives its rows, and a row of a + // row vector is the vector again. + foreach (var entry in from i in Enumerable.Range(0, m.RowCount) from j in Enumerable.Range(0, m.ColumnCount) select m[i, j]) + { + var check = Of(entry, dims); + if (!check.IsConsistent) + return check; + if (IsScaleFree(entry)) + continue; + if (common is null) + common = check.Dimension; + else if (common != check.Dimension) + return DimensionCheck.Unknown(m, $"the entries of {m} have different dimensions, {common} and {check.Dimension}, and a matrix is read only when its entries share one"); + } + return DimensionCheck.Ok(common ?? Dimension.Dimensionless); + } + + // The determinant of an n by n matrix of entries of dimension D is a sum of products of + // n entries, so it has dimension D^n. That needs n, which only a written matrix shows. + private static DimensionCheck Determinant(Entity at, IReadOnlyDictionary dims, Entity a) + => Then(Of(a, dims), da => + da.IsDimensionless ? Pure + : a is Matrix { RowCount: var rows, ColumnCount: var columns } && rows == columns + ? DimensionCheck.Ok(da.Pow(ERational.FromInt32(rows))) + : DimensionCheck.Unknown(at, $"the determinant of a matrix of entries of dimension {da} has that dimension to the order of the matrix, and the order of {a} is not known")); + private static DimensionCheck Cases(Entity at, IReadOnlyDictionary dims, Piecewise pw) { foreach (var c in pw.Cases) { - var condition = Of(c.Predicate, dims); + var condition = MustBePure(at, c.Predicate, dims); if (!condition.IsConsistent) return condition; } return Agree(at, "cases of one piecewise", dims, pw.Cases.Select(c => c.Expression).ToArray()); } - private static DimensionCheck AllDimensionless(Entity at, IReadOnlyDictionary dims, bool mustBePure) + private static DimensionCheck AllPure(Entity at, IReadOnlyDictionary dims) { foreach (var child in at.DirectChildren) { - var check = Of(child, dims); + var check = MustBePure(at, child, dims); if (!check.IsConsistent) return check; - if (mustBePure && !check.Dimension!.IsDimensionless) - return DimensionCheck.Bad(at, $"{child} has dimension {check.Dimension}, and {at.GetType().Name.TrimEnd('f')} only takes a pure number"); } - return DimensionCheck.Ok(Dimension.Dimensionless); + return Pure; } } } diff --git a/Sources/Tests/UnitTests/Convenience/DimensionsTest.cs b/Sources/Tests/UnitTests/Convenience/DimensionsTest.cs index 691ee7afd..33405ef03 100644 --- a/Sources/Tests/UnitTests/Convenience/DimensionsTest.cs +++ b/Sources/Tests/UnitTests/Convenience/DimensionsTest.cs @@ -7,6 +7,7 @@ using System; using System.Collections.Generic; +using System.Linq; using AngouriMath.Core; using AngouriMath.Extensions; using Xunit; @@ -122,6 +123,43 @@ public void PipeFlowHasTheReynoldsNumber() Assert.Equal("mu / (rho * v * d)", group.ToString()); } + // Drag on a sphere: force, density, speed, diameter, viscosity. Five variables over the + // three dimensions M, L, T, all reached, so two groups: the drag coefficient's and the + // Reynolds number's. + [Fact] + public void DragHasTwoGroups() + { + var dims = new Dictionary + { + ["F"] = M * L / T.Pow(2), ["rho"] = M / L.Pow(3), ["v"] = L / T, ["d"] = L, ["mu"] = M / (L * T), + }; + var groups = MathS.Dimensions.DimensionlessGroups(new Variable[] { "rho", "v", "d", "F", "mu" }, dims); + Assert.Equal(new[] { "F / (rho * v ^ 2 * d ^ 2)", "mu / (rho * v * d)" }, groups.Select(g => g.ToString())); + foreach (var group in groups) + Assert.Equal("Consistent: 1", MathS.Dimensions.Of(group, dims).ToString()); + } + + // Water waves, from omega^2 = g k tanh(k h): the relation is consistent, the phase of + // the shallow-water slip omega = sqrt(g k h) is not, and wave number, gravity, amplitude, + // depth and time give the groups k A, k h and g k t^2. + [Fact] + public void WaterWaves() + { + var dims = new Dictionary + { + ["omega"] = Dimension.Dimensionless / T, ["g"] = L / T.Pow(2), ["k"] = Dimension.Dimensionless / L, + ["h"] = L, ["A"] = L, ["x"] = L, ["t"] = T, + }; + Assert.Equal("Consistent: 1", MathS.Dimensions.Of("omega^2 = g k tanh(k h)", dims).ToString()); + Assert.Equal("Consistent: L", MathS.Dimensions.Of("A sin(k x - omega t)", dims).ToString()); + Assert.Equal(DimensionStatus.Inconsistent, MathS.Dimensions.Of("A sin(k x - sqrt(g k h) t)", dims).Status); + + var groups = MathS.Dimensions.DimensionlessGroups(new Variable[] { "k", "g", "A", "h", "t" }, dims); + Assert.Equal(new[] { "k * A", "k * h", "k * g * t ^ 2" }, groups.Select(g => g.ToString())); + foreach (var group in groups) + Assert.Equal("Consistent: 1", MathS.Dimensions.Of(group, dims).ToString()); + } + [Fact] public void EveryGroupIsAPureNumber() { @@ -141,6 +179,262 @@ public void IndependentDimensionsHaveNoGroup() public void AnUndeclaredVariableIsRefused() => Assert.Throws(() => MathS.Dimensions.DimensionlessGroups(new Variable[] { "h", "w" }, Mechanics)); + [Theory] + [InlineData("iverson(h > d)", "1")] + [InlineData("dot([h, d], [v, v])", "L^2 T^-1")] + [InlineData("cross([h, d, l], [v, v, v])", "L^2 T^-1")] + [InlineData("abs([v, v])", "L T^-1")] + [InlineData("norm([h, d], 1)", "L")] + [InlineData("det([[h, d], [d, h]])", "L^2")] + [InlineData("trace([[h, d], [d, h]])", "L")] + [InlineData("zeta(h / d)", "1")] + [InlineData("erf(t / tau)", "1")] + [InlineData("tanh(h / d)", "1")] + [InlineData("conj(v)", "L T^-1")] + [InlineData("integral(v, t, 0, tau)", "L")] + [InlineData("product(h, n, 1, 3)", "L^3")] + [InlineData("sum(h / n, n, 1, +oo)", "L")] + public void TheRulesOfLaterNodes(string expr, string dimension) + { + var check = Check(expr); + Assert.True(check.IsConsistent, check.ToString()); + Assert.Equal(dimension, check.Dimension!.ToString()); + } + + [Theory] + [InlineData("zeta(h)")] + [InlineData("erf(t)")] + [InlineData("tanh(h)")] + [InlineData("iverson(h > t)")] + [InlineData("dot([h, d], [v, v]) = h")] + [InlineData("integral(v, t, 0, h)")] + public void LaterNodesRejectAQuantityWhereItCannotBe(string expr) + => Assert.Equal(DimensionStatus.Inconsistent, Check(expr).Status); + + // A product of a symbolic number of dimensional terms, the determinant of a matrix of + // unknown order, a vector of mixed dimensions and a variable ranging over a set that + // fixes no dimension each leave the answer open. + [Fact] + public void WhatTheLaterNodesCannotSettleIsUndetermined() + { + Variable k = "k", w = "w"; + Assert.Equal(DimensionStatus.Undetermined, MathS.Dimensions.Of(new Productf("h", k, 1, "n"), Mechanics).Status); + Assert.Equal(DimensionStatus.Undetermined, MathS.Dimensions.Of(new Determinantf("h"), Mechanics).Status); + Assert.Equal(DimensionStatus.Undetermined, MathS.Dimensions.Of(MathS.Vector("h", "v"), Mechanics).Status); + Assert.Equal(DimensionStatus.Undetermined, MathS.Dimensions.Of(new Maximumf(k, k, MathS.Interval(0, Number.Real.PositiveInfinity)), Mechanics).Status); + Assert.Equal(DimensionStatus.Undetermined, MathS.Dimensions.Of(new ProductOverSetf("h", k, MathS.Sets.Z), Mechanics).Status); + Assert.Equal(DimensionStatus.Undetermined, MathS.Dimensions.Of(new Set.Inf(w, MathS.Interval(0, "h")), Mechanics).Status); + } + + // l in RR says a length is real, and is not a claim that it is a pure number; a sum + // over the integers makes its undeclared index one. + [Fact] + public void ANumberSetFitsAQuantityAndMakesAnIndexAPureNumber() + { + Variable k = "k"; + Assert.True(MathS.Dimensions.Of(new Set.Inf("h", MathS.Sets.R), Mechanics).IsConsistent); + Assert.Equal("L", MathS.Dimensions.Of(new SumOverSetf(new Divf("h", new Powf(k, 2)), k, MathS.Sets.PositiveIntegers), Mechanics).Dimension!.ToString()); + // A declared variable ranging over a set whose members measure something else. + Assert.Equal(DimensionStatus.Inconsistent, MathS.Dimensions.Of(new Maximumf("h", "h", MathS.Interval(0, "t")), Mechanics).Status); + } + + // ---------------------------------------------------------------- every node type + + private static readonly Variable X = "x", Y = "y", Tt = "t", V = "v", N = "n", K = "k"; + + private static readonly Dictionary Nodes = new() + { + [X] = L, [Y] = L, [Tt] = T, [V] = L / T, [N] = Dimension.Dimensionless, + }; + + private const string NotRead = "not read"; + + /// + /// One sample of every concrete node type, with the verdict it gets with x and y lengths, + /// t a time, v a speed and n a pure number. marks a node the check + /// reports undetermined because it does not read it. + /// + private static readonly (Entity Sample, string Verdict)[] EveryNode = + { + (X, "Consistent: L"), + (MathS.pi, "Consistent: 1"), + (3, "Consistent: 1"), + (Number.Rational.Create(1, 2), "Consistent: 1"), + (MathS.pi.Evaled, "Consistent: 1"), + (Number.Complex.Create(1, 2), "Consistent: 1"), + (Entity.Boolean.True, "Consistent: 1"), + + (new Sumf(X, Y), "Consistent: L"), + (new Minusf(X, Tt), "Inconsistent"), + (new Mulf(X, Tt), "Consistent: L T"), + (new Divf(X, Tt), "Consistent: L T^-1"), + (new Powf(X, 2), "Consistent: L^2"), + (new Modf(X, Y), "Consistent: L"), + (new Maxf(X, Tt), "Inconsistent"), + (new Minf(X, Y), "Consistent: L"), + + (new Absf(V), "Consistent: L T^-1"), + (new Conjugatef(X), "Consistent: L"), + (new Ref(X), "Consistent: L"), + (new Imf(X), "Consistent: L"), + (new Signumf(X), "Consistent: 1"), + (new Argf(X), "Consistent: 1"), + + // A length where a pure number is needed. + (new Sinf(X), "Inconsistent"), + (new Cosf(X), "Inconsistent"), + (new Tanf(X), "Inconsistent"), + (new Cotanf(X), "Inconsistent"), + (new Secantf(X), "Inconsistent"), + (new Cosecantf(X), "Inconsistent"), + (new Arcsinf(X), "Inconsistent"), + (new Arccosf(X), "Inconsistent"), + (new Arctanf(X), "Inconsistent"), + (new Arccotanf(X), "Inconsistent"), + (new Arcsecantf(X), "Inconsistent"), + (new Arccosecantf(X), "Inconsistent"), + (new Logf(N, X), "Inconsistent"), + (new Eif(X), "Inconsistent"), + (new Sif(X), "Inconsistent"), + (new Cif(X), "Inconsistent"), + (new Shif(X), "Inconsistent"), + (new Chif(X), "Inconsistent"), + (new Lif(X), "Inconsistent"), + (new Erff(X), "Inconsistent"), + (new Erfcf(X), "Inconsistent"), + (new Erfif(X), "Inconsistent"), + (new LambertWf(N, X), "Inconsistent"), + (new Polygammaf(N, X), "Inconsistent"), + (new Zetaf(X, N), "Inconsistent"), + (new Betaf(X, N), "Inconsistent"), + (new IncompleteGammaf(N, X), "Inconsistent"), + (new Factorialf(X), "Inconsistent"), + (new DoubleFactorialf(X), "Inconsistent"), + (new Binomialf(X, N), "Inconsistent"), + (new FallingFactorialf(X, N), "Inconsistent"), + (new RisingFactorialf(X, N), "Inconsistent"), + (new CatalanNumberf(X), "Inconsistent"), + (new HarmonicNumberf(X, N), "Inconsistent"), + (new Floorf(X), "Inconsistent"), + (new Ceilf(X), "Inconsistent"), + (new Roundf(X), "Inconsistent"), + (new Gcdf(X, N), "Inconsistent"), + (new Lcmf(X, N), "Inconsistent"), + (new Phif(X), "Inconsistent"), + (new Mobiusf(X), "Inconsistent"), + (new DivisorSigmaf(N, X), "Inconsistent"), + (new PrimeNuf(X), "Inconsistent"), + (new PrimeOmegaf(X), "Inconsistent"), + (new PrimePif(X), "Inconsistent"), + (new Primef(X), "Inconsistent"), + (new Valuationf(X, N), "Inconsistent"), + (new PrimeFactorizationf(X), "Inconsistent"), + (new Alephf(X), "Inconsistent"), + (new Iversonf(X), "Inconsistent"), + (new Andf(X, Entity.Boolean.True), "Inconsistent"), + (new Orf(new Greaterf(X, Y), new Lessf(Tt, 0)), "Consistent: 1"), + (new Notf(X), "Inconsistent"), + (new Xorf(new Greaterf(X, Y), Entity.Boolean.False), "Consistent: 1"), + (new Impliesf(new Greaterf(X, Y), new Greaterf(X, Tt)), "Inconsistent"), + (new Dividesf(X, N), "Inconsistent"), + (new Congruentf(X, N, 3), "Inconsistent"), + + (new Cardf(MathS.Sets.Finite(X, Y)), "Consistent: 1"), + (MathS.Vector(X, Y), "Consistent: L"), + (new DotProductf(MathS.Vector(V, V), MathS.Vector(Tt, Tt)), "Consistent: L"), + (new CrossProductf(MathS.Vector(X, X, X), MathS.Vector(V, V, V)), "Consistent: L^2 T^-1"), + (new Normf(MathS.Vector(X, Y), 2), "Consistent: L"), + (new Tracef(MathS.Matrix(new Entity[,] { { X, Y }, { Y, X } })), "Consistent: L"), + (new Transposef(MathS.Vector(X, Y)), "Consistent: L"), + (new MatrixEntryf(MathS.Vector(X, Y), 1, 1), "Consistent: L"), + (new Determinantf(MathS.Matrix(new Entity[,] { { X, Y }, { Y, X } })), "Consistent: L^2"), + + (MathS.Derivative(X, Tt, 2), "Consistent: L T^-2"), + (MathS.PartialDerivative(X, Tt, 1), "Consistent: L T^-1"), + (MathS.Integral(V, Tt, 0, Tt), "Consistent: L"), + (MathS.Limit(X / Tt, Tt, 0), "Consistent: L T^-1"), + (new Summationf(X, K, 1, N), "Consistent: L"), + (new Productf(X, K, 1, 3), "Consistent: L^3"), + (new SumOverSetf(K * X, K, MathS.Sets.Finite(1, 2)), "Consistent: L"), + (new ProductOverSetf(X, K, MathS.Sets.Finite(1, 2, 3)), "Consistent: L^3"), + (new Maximumf(K, K, MathS.Interval(0, Y)), "Consistent: L"), + (new Minimumf(K * V, K, MathS.Interval(0, Tt)), "Consistent: L"), + + (new Providedf(X, new Greaterf(Tt, 0)), "Consistent: L"), + (MathS.Piecewise((X, new Greaterf(Tt, 0)), (Y, new LessOrEqualf(Tt, 0))), "Consistent: L"), + (new Equalsf(X, Y), "Consistent: 1"), + (new Lessf(X, Tt), "Inconsistent"), + (new Greaterf(V, 0), "Consistent: 1"), + (new LessOrEqualf(X, Y), "Consistent: 1"), + (new GreaterOrEqualf(Tt, V), "Inconsistent"), + (new Set.Inf(X, MathS.Interval(0, Y)), "Consistent: 1"), + (new Set.Subsetf(MathS.Interval(0, X), MathS.Interval(0, Tt)), "Inconsistent"), + (new Forallf(K, MathS.Sets.R, new Greaterf(K * K, 0)), "Consistent: 1"), + (new Existsf(K, MathS.Interval(0, Y), new Greaterf(K, X)), "Consistent: 1"), + (new ExistsUniquef(K, MathS.Interval(0, Y), new Greaterf(K, Tt)), "Inconsistent"), + + // A set is not a quantity; it is read only where a variable ranges over it. + (MathS.Sets.Finite(X, Y), NotRead), + (MathS.Interval(0, X), NotRead), + (new Set.ConditionalSet(X, new Greaterf(X, 0)), NotRead), + (MathS.Sets.R, NotRead), + (MathS.Sets.C, NotRead), + (MathS.Sets.Q, NotRead), + (MathS.Sets.Z, NotRead), + (MathS.Sets.NonNegativeIntegers, NotRead), + (MathS.Sets.PositiveIntegers, NotRead), + (MathS.Sets.Primes, NotRead), + (Set.SpecialSet.Create(Domain.Boolean), NotRead), + (new Set.Unionf(MathS.Interval(0, X), MathS.Interval(0, Y)), NotRead), + (new Set.Intersectionf(MathS.Interval(0, X), MathS.Interval(0, Y)), NotRead), + (new Set.SetMinusf(MathS.Interval(0, X), MathS.Interval(0, Y)), NotRead), + (new Set.Powersetf(MathS.Sets.Finite(X)), NotRead), + (new Set.PrimeFactorsf(N), NotRead), + (new Set.IndexedUnionf(K, MathS.Sets.Finite(1, 2), MathS.Interval(0, K * X)), NotRead), + (new Set.IndexedIntersectionf(K, MathS.Sets.Finite(1, 2), MathS.Interval(0, K * X)), NotRead), + (new Argmaxf(K, K, MathS.Interval(0, Y)), NotRead), + (new Argminf(K, K, MathS.Interval(0, Y)), NotRead), + // A function, and a function applied, whose dimensions nothing declares. + (MathS.Lambda(X, X), NotRead), + (MathS.Apply(MathS.Var("f"), X), NotRead), + }; + + private static string Verdict(DimensionCheck check) + => check.Status switch + { + DimensionStatus.Consistent => check.ToString(), + DimensionStatus.Undetermined when check.Reason.EndsWith("is not read by the dimension check", StringComparison.Ordinal) => NotRead, + var status => status.ToString(), + }; + + /// + /// Every node type has a sample above and the check gives it the verdict listed. + /// + /// + /// The walk reads a node only where an arm names it, so a node type added to the + /// library is reported undetermined rather than read as a pure number by default; and + /// this fails on it, by name, until a sample and a verdict are written for it here, + /// which is where someone decides what its dimension is. + /// + [Fact] + public void EveryNodeTypeHasADecidedReading() + { + var types = typeof(Entity).Assembly.GetTypes() + .Where(t => !t.IsAbstract && typeof(Entity).IsAssignableFrom(t)) + .Select(t => t.Name).ToHashSet(); + var sampled = EveryNode.Select(e => e.Sample.GetType().Name).ToHashSet(); + Assert.True(types.SetEquals(sampled), + "node types with no sample: " + string.Join(", ", types.Except(sampled).OrderBy(n => n, StringComparer.Ordinal)) + + "; samples of no node type: " + string.Join(", ", sampled.Except(types))); + + var wrong = EveryNode + .Select(e => (e.Sample, e.Verdict, Actual: MathS.Dimensions.Of(e.Sample, Nodes))) + .Where(e => Verdict(e.Actual) != e.Verdict) + .Select(e => $"{e.Sample.GetType().Name} {e.Sample}: expected {e.Verdict}, got {e.Actual}") + .ToList(); + Assert.True(wrong.Count is 0, string.Join("\n", wrong)); + } + [Fact] public void DimensionArithmetic() {