Skip to content

Commit db1568c

Browse files
Rafael-SOWNetclaude
andcommitted
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 <noreply@anthropic.com>
1 parent ee728a4 commit db1568c

8 files changed

Lines changed: 896 additions & 0 deletions

File tree

‎Sources/.editorconfig‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1163,6 +1163,15 @@ file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed
11631163
[Tests/UnitTests/Convenience/ShadersTest.cs]
11641164
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
11651165

1166+
[AngouriMath/Functions/Dimensions/*.cs]
1167+
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
1168+
1169+
[AngouriMath/Convenience/MathS.Dimensions.cs]
1170+
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
1171+
1172+
[Tests/UnitTests/Convenience/DimensionsTest.cs]
1173+
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
1174+
11661175
[Tests/UnitTests/Convenience/PrimeFactorizationNodeTest.cs]
11671176
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
11681177

Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
//
2+
// Copyright (c) 2019-2026 Angouri.
3+
// AngouriMath is licensed under MIT.
4+
// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.
5+
// Website: https://am.angouri.org.
6+
//
7+
8+
9+
10+
namespace AngouriMath
11+
{
12+
using static Entity;
13+
14+
partial class MathS
15+
{
16+
/// <summary>
17+
/// Dimensional analysis: whether a formula is physically meaningful, what kind of
18+
/// quantity it produces, and which combinations of its variables are pure numbers.
19+
/// </summary>
20+
/// <remarks>
21+
/// <para>
22+
/// A variable is a symbol, and nothing in an <see cref="Entity"/> says that <c>v</c>
23+
/// is a speed. The caller says so, with a map from each variable to its
24+
/// <see cref="Dimension"/>, and the check reads the formula against it. The map is
25+
/// passed rather than attached to the variables, so the same expression can be read
26+
/// under different assignments, and nothing about how an expression prints, parses or
27+
/// simplifies changes.
28+
/// </para>
29+
/// <para>
30+
/// This complements a units library rather than replacing one. UnitsNet and its kind
31+
/// check a <i>value</i>: a length divided by a time is a speed. Neither can look at
32+
/// <c>sqrt(2 g h)</c> and say whether it is one, and that is what this does.
33+
/// </para>
34+
/// <para>
35+
/// <b>Undetermined is not a verdict.</b> An undeclared variable, or a node the check does
36+
/// not read, gives <see cref="DimensionStatus.Undetermined"/>, never a guess.
37+
/// </para>
38+
/// </remarks>
39+
public static class Dimensions
40+
{
41+
/// <summary>
42+
/// The dimension of <paramref name="expr"/> as written, or the subexpression where
43+
/// it stops making physical sense.
44+
/// </summary>
45+
/// <param name="expr">The formula, an expression or a statement.</param>
46+
/// <param name="dimensions">The dimension of each variable it mentions. The constants
47+
/// <c>pi</c> and <c>e</c> and every number are pure numbers and need no entry.</param>
48+
/// <returns>
49+
/// <see cref="DimensionStatus.Consistent"/> with the dimension of the result — a
50+
/// statement such as an equation is a pure number once its sides agree;
51+
/// <see cref="DimensionStatus.Inconsistent"/> with the subexpression at fault and why;
52+
/// or <see cref="DimensionStatus.Undetermined"/> where it could not be settled.
53+
/// </returns>
54+
/// <remarks>
55+
/// <para>
56+
/// A literal <c>0</c> or <c>oo</c> fits any dimension where it is added or compared,
57+
/// since it is the same quantity in every unit: <c>v = 0</c> is meaningful.
58+
/// </para>
59+
/// <para>
60+
/// Nothing is simplified first. <c>sin(x) - sin(x)</c> with <c>x</c> a length is
61+
/// inconsistent, although it simplifies to <c>0</c>.
62+
/// </para>
63+
/// </remarks>
64+
/// <example>
65+
/// <code>
66+
/// using System;
67+
/// using System.Collections.Generic;
68+
/// using AngouriMath;
69+
/// using AngouriMath.Core;
70+
///
71+
/// var acceleration = Dimension.Length / Dimension.Time.Pow(2);
72+
/// var dims = new Dictionary&lt;Entity.Variable, Dimension&gt;
73+
/// {
74+
/// ["g"] = acceleration, ["h"] = Dimension.Length, ["t"] = Dimension.Time,
75+
/// };
76+
/// Console.WriteLine(MathS.Dimensions.Of("sqrt(2 g h)", dims));
77+
/// Console.WriteLine(MathS.Dimensions.Of("h - g t^2 / 2 = 0", dims));
78+
/// Console.WriteLine(MathS.Dimensions.Of("h + g t", dims));
79+
/// </code>
80+
/// Prints
81+
/// <code>
82+
/// Consistent: L T^-1
83+
/// Consistent: 1
84+
/// Inconsistent at h + g * t: h has dimension L and g * t has dimension L T^-1, so they cannot be added
85+
/// </code>
86+
/// </example>
87+
public static DimensionCheck Of(Entity expr, IReadOnlyDictionary<Variable, Dimension> dimensions)
88+
=> DimensionAnalysis.Of(expr, dimensions);
89+
90+
/// <summary>
91+
/// A basis of the dimensionless products of powers of <paramref name="variables"/>:
92+
/// the Buckingham π groups.
93+
/// </summary>
94+
/// <param name="variables">
95+
/// The variables of the problem, each declared in <paramref name="dimensions"/>.
96+
/// Their order chooses the basis: the earlier ones are the repeating variables, and
97+
/// each later variable appears to the first power in exactly one group.
98+
/// </param>
99+
/// <param name="dimensions">The dimension of each variable.</param>
100+
/// <returns>
101+
/// One group per variable beyond the rank of the dimension matrix, each written with
102+
/// the smallest whole powers and each checked to be a pure number before it is
103+
/// returned. An empty list means no product of these variables is dimensionless.
104+
/// </returns>
105+
/// <remarks>
106+
/// A model whose output depends on these variables depends on them only through
107+
/// the groups, which is what makes a scale model of a ship mean anything, and what
108+
/// reduces the parameters a simulation has to be tuned over.
109+
/// </remarks>
110+
/// <example>
111+
/// <code>
112+
/// using System;
113+
/// using System.Collections.Generic;
114+
/// using AngouriMath;
115+
/// using AngouriMath.Core;
116+
///
117+
/// // Flow in a pipe: density, speed, diameter, viscosity.
118+
/// var dims = new Dictionary&lt;Entity.Variable, Dimension&gt;
119+
/// {
120+
/// ["rho"] = Dimension.Mass / Dimension.Length.Pow(3),
121+
/// ["v"] = Dimension.Length / Dimension.Time,
122+
/// ["d"] = Dimension.Length,
123+
/// ["mu"] = Dimension.Mass / (Dimension.Length * Dimension.Time),
124+
/// };
125+
/// foreach (var group in MathS.Dimensions.DimensionlessGroups(new Entity.Variable[] { "rho", "v", "d", "mu" }, dims))
126+
/// Console.WriteLine(group);
127+
/// </code>
128+
/// Prints
129+
/// <code>
130+
/// mu / (rho * v * d)
131+
/// </code>
132+
/// </example>
133+
public static IReadOnlyList<Entity> DimensionlessGroups(IReadOnlyList<Variable> variables, IReadOnlyDictionary<Variable, Dimension> dimensions)
134+
=> AngouriMath.Functions.DimensionlessGroups.Of(variables, dimensions);
135+
}
136+
}
137+
}
Lines changed: 174 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,174 @@
1+
//
2+
// Copyright (c) 2019-2026 Angouri.
3+
// AngouriMath is licensed under MIT.
4+
// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.
5+
// Website: https://am.angouri.org.
6+
//
7+
8+
using System;
9+
using PeterO.Numbers;
10+
11+
namespace AngouriMath.Core
12+
{
13+
/// <summary>
14+
/// One of the seven base dimensions of the SI, in the order the SI brochure lists them.
15+
/// </summary>
16+
public enum BaseDimension
17+
{
18+
/// <summary>L, measured in metres.</summary>
19+
Length,
20+
/// <summary>M, measured in kilograms.</summary>
21+
Mass,
22+
/// <summary>T, measured in seconds.</summary>
23+
Time,
24+
/// <summary>I, measured in amperes.</summary>
25+
Current,
26+
/// <summary>Θ, measured in kelvins.</summary>
27+
Temperature,
28+
/// <summary>N, measured in moles.</summary>
29+
Amount,
30+
/// <summary>J, measured in candelas.</summary>
31+
LuminousIntensity,
32+
}
33+
34+
/// <summary>
35+
/// A physical dimension: a product of powers of the seven <see cref="BaseDimension"/>s,
36+
/// such as <c>L T^-2</c> for an acceleration.
37+
/// </summary>
38+
/// <remarks>
39+
/// <para>
40+
/// The exponents are rationals, not integers, because a square root of a dimensional
41+
/// quantity is a legitimate intermediate: <c>sqrt(L)</c> appears inside the period of a
42+
/// pendulum before it is divided by <c>sqrt(L T^-2)</c>.
43+
/// </para>
44+
/// <para>
45+
/// A dimension says what kind of quantity something is and nothing about its unit: a
46+
/// metre and a foot are both <see cref="Length"/>. Units and their conversions are a
47+
/// separate concern, which UnitsNet and its kind already handle.
48+
/// </para>
49+
/// </remarks>
50+
public sealed class Dimension : IEquatable<Dimension>
51+
{
52+
private const int Count = 7;
53+
[ConstantField] private static readonly string[] symbols = { "L", "M", "T", "I", "Θ", "N", "J" };
54+
private readonly ERational[] exponents;
55+
56+
// PeterO keeps a rational as it was computed, 2/2 included; reducing here is what lets
57+
// ToString and IsIntegral read the numerator and denominator directly.
58+
private Dimension(ERational[] exponents)
59+
=> this.exponents = exponents.Select(e =>
60+
{
61+
var g = e.Numerator.Gcd(e.Denominator);
62+
return g.IsZero || g.Equals(EInteger.One) ? e : ERational.Create(e.Numerator / g, e.Denominator / g);
63+
}).ToArray();
64+
65+
private static Dimension Base(BaseDimension b)
66+
{
67+
var exponents = Enumerable.Repeat(ERational.Zero, Count).ToArray();
68+
exponents[(int)b] = ERational.One;
69+
return new Dimension(exponents);
70+
}
71+
72+
/// <summary>A pure number: a ratio, an angle in radians, a count.</summary>
73+
[ConstantField] public static readonly Dimension Dimensionless = new(Enumerable.Repeat(ERational.Zero, Count).ToArray());
74+
/// <summary>L.</summary>
75+
[ConstantField] public static readonly Dimension Length = Base(BaseDimension.Length);
76+
/// <summary>M.</summary>
77+
[ConstantField] public static readonly Dimension Mass = Base(BaseDimension.Mass);
78+
/// <summary>T.</summary>
79+
[ConstantField] public static readonly Dimension Time = Base(BaseDimension.Time);
80+
/// <summary>I.</summary>
81+
[ConstantField] public static readonly Dimension Current = Base(BaseDimension.Current);
82+
/// <summary>Θ.</summary>
83+
[ConstantField] public static readonly Dimension Temperature = Base(BaseDimension.Temperature);
84+
/// <summary>N.</summary>
85+
[ConstantField] public static readonly Dimension Amount = Base(BaseDimension.Amount);
86+
/// <summary>J.</summary>
87+
[ConstantField] public static readonly Dimension LuminousIntensity = Base(BaseDimension.LuminousIntensity);
88+
89+
/// <summary>
90+
/// The dimension with the given exponent on each base dimension, in the order of
91+
/// <see cref="BaseDimension"/>; unlisted trailing exponents are zero.
92+
/// </summary>
93+
/// <example>
94+
/// <code>
95+
/// using System;
96+
/// using AngouriMath.Core;
97+
///
98+
/// Console.WriteLine(Dimension.Create(1, 1, -2));
99+
/// </code>
100+
/// Prints
101+
/// <code>
102+
/// L M T^-2
103+
/// </code>
104+
/// </example>
105+
public static Dimension Create(params int[] exponents)
106+
{
107+
if (exponents.Length > Count)
108+
throw new ArgumentException($"There are {Count} base dimensions, and {exponents.Length} exponents were given.", nameof(exponents));
109+
var e = Enumerable.Repeat(ERational.Zero, Count).ToArray();
110+
for (var k = 0; k < exponents.Length; k++)
111+
e[k] = ERational.FromInt32(exponents[k]);
112+
return new Dimension(e);
113+
}
114+
115+
/// <summary>The exponent of <paramref name="b"/>.</summary>
116+
public Entity.Number.Rational this[BaseDimension b] => Entity.Number.Rational.Create(exponents[(int)b]);
117+
118+
/// <summary>Whether every exponent is zero.</summary>
119+
public bool IsDimensionless => exponents.All(e => e.IsZero);
120+
121+
/// <summary>Whether every exponent is a whole number, as a unit system's base units need.</summary>
122+
public bool IsIntegral => exponents.All(e => e.Denominator.Equals(EInteger.One));
123+
124+
/// <summary>The product of two dimensions: exponents add.</summary>
125+
public static Dimension operator *(Dimension a, Dimension b)
126+
=> new(a.exponents.Zip(b.exponents, (x, y) => x + y).ToArray());
127+
128+
/// <summary>The quotient of two dimensions: exponents subtract.</summary>
129+
public static Dimension operator /(Dimension a, Dimension b)
130+
=> new(a.exponents.Zip(b.exponents, (x, y) => x - y).ToArray());
131+
132+
/// <summary>This dimension to a rational power: every exponent is multiplied by it.</summary>
133+
public Dimension Pow(Entity.Number.Rational power) => Pow(power.ERational);
134+
135+
internal Dimension Pow(ERational power) => new(exponents.Select(e => e * power).ToArray());
136+
137+
internal ERational Exponent(int k) => exponents[k];
138+
139+
/// <inheritdoc/>
140+
public bool Equals(Dimension? other)
141+
=> other is not null && exponents.Zip(other.exponents, (x, y) => x.CompareTo(y) == 0).All(eq => eq);
142+
143+
/// <inheritdoc/>
144+
public override bool Equals(object? obj) => Equals(obj as Dimension);
145+
146+
/// <inheritdoc/>
147+
public override int GetHashCode()
148+
=> exponents.Aggregate(17, (h, e) => unchecked(h * 31 + e.Numerator.GetHashCode() * 7 + e.Denominator.GetHashCode()));
149+
150+
/// <summary>Equality of every exponent.</summary>
151+
public static bool operator ==(Dimension? a, Dimension? b) => a is null ? b is null : a.Equals(b);
152+
153+
/// <summary>Inequality of some exponent.</summary>
154+
public static bool operator !=(Dimension? a, Dimension? b) => !(a == b);
155+
156+
/// <summary>
157+
/// The base dimensions with nonzero exponents, in SI order, as <c>L M T^-2</c>;
158+
/// <c>1</c> for <see cref="Dimensionless"/>.
159+
/// </summary>
160+
public override string ToString()
161+
{
162+
var parts = new List<string>();
163+
for (var k = 0; k < Count; k++)
164+
{
165+
var e = exponents[k];
166+
if (e.IsZero) continue;
167+
parts.Add(e.CompareTo(ERational.One) == 0 ? symbols[k]
168+
: e.Denominator.Equals(EInteger.One) ? $"{symbols[k]}^{e.Numerator}"
169+
: $"{symbols[k]}^({e.Numerator}/{e.Denominator})");
170+
}
171+
return parts.Count == 0 ? "1" : string.Join(" ", parts);
172+
}
173+
}
174+
}

0 commit comments

Comments
 (0)