Upgraded AngouriMath to v2.8.0 (#1235)

This commit is contained in:
Thorsten Sommer authored and GitHub committed 2026-11-25 18:45:24 +01:00
1 parent fae3ceb840
commit 506c06fbfc
24 files changed
+974 -105

No files matched your search

@@ -1,3 +1,5 @@
using AIStudio.Tools.Mathematics;
using AngouriMath;
using AngouriMath.Core;
using AngouriMath.Core.Exceptions;
@@ -11,7 +13,7 @@ namespace AIStudio.Tests.Tools.Mathematics;
/// </summary>
/// <remarks>
/// AngouriMath puts correct answers ahead of backward compatibility, and says so: the release notes of
/// 2.6.0 list 516 changed answers, fourteen of them silent, where the call still succeeds and returns
/// 2.7.0 and 2.8.0 list 221 changed answers, 147 of them silent, where the call still succeeds and returns
/// something else. An update which changes anything below fails here first, not in a chat. Each test
/// names what AngouriMath does; where the tools have to guard against it, the test says so.
/// </remarks>
@@ -20,6 +22,50 @@ public sealed class AngouriMathBehaviorTests
{
private static readonly Entity.Variable X = MathS.Var("x");
/// <summary>
/// The operators and other tokens of the parser which are no function.
/// </summary>
private static readonly string[] OPERATORS =
[
"!", "!!", "!!!", "#", "&", "(", "(|", ")", "*", "+", "+oo", ",", "-", "->", "-oo", "...", "/", "/\\", ":", ";", "<", "<=", "<>", "=", "=>",
">", ">=", "NaN", "[", "\\", "\\/", "]", "]T", "^", "and", "divides", "exists", "exists!", "forall", "implies", "in", "intersect", "mod",
"not", "or", "provided", "setsubtract", "subset", "superset", "unite", "xor", "{", "|", "|)", "}", "…", "∀", "∃", "∃!", "≡", "⊆", "⊇"
];
/// <summary>
/// The functions of the parser which MathExpressionReader passes on, besides UNSUPPORTED_FUNCTIONS.
/// </summary>
private static readonly string[] FUNCTIONS_PASSED_ON =
[
"Chi", "Ci", "Ei", "Shi", "Si", "abs", "acos", "acosec", "acosech", "acosh", "acot", "acotan", "acotanh", "acoth", "acsc", "acsch", "aleph",
"apply", "arccos", "arccosec", "arccosech", "arccosh", "arccot", "arccotan", "arccotanh", "arccsc", "arch", "arcosech", "arcosh", "arcotanh",
"arcoth", "arcsch", "arcsec", "arcsech", "arcsin", "arcsinh", "arctan", "arctanh", "arcth", "argmax", "argmin", "arsch", "arsech", "arsh",
"arsinh", "artanh", "arth", "asec", "asech", "asin", "asinh", "atan", "atanh", "binomial", "card", "cbrt", "ceil", "ceiling", "ch",
"complement", "cos", "cosec", "cosech", "cosh", "cot", "cotan", "cotanh", "coth", "csc", "csch", "cth", "derivative", "digamma", "domain",
"erf", "erfc", "erfi", "exp", "factorial", "floor", "gamma", "gcd", "image", "integral", "intersection", "iverson", "lambda", "lambertw",
"lcm", "li", "limit", "limitleft", "limitright", "ln", "log", "log10", "log2", "max", "min", "phi", "piecewise", "polygamma", "pow",
"powerset", "preimage", "prime", "product", "productlog", "round", "sch", "sec", "sech", "sgn", "sh", "sign", "signum", "sin", "sinh", "sqr",
"sqrt", "sum", "tan", "tanh", "th", "trunc", "union", "valuation", "φ", "ϕ"
];
/// <summary>
/// The kinds of nodes which MathExpressionReader passes on, besides UNSUPPORTED_NODE_TYPES.
/// </summary>
private static readonly string[] NODE_TYPES_PASSED_ON =
[
"Absf", "Alephf", "Andf", "Application", "Arccosecantf", "Arccosf", "Arccotanf", "Arcsecantf", "Arcsinf", "Arctanf", "Argmaxf", "Argminf",
"Binomialf", "Boolean", "Cardf", "Ceilf", "Chif", "Cif", "Congruentf", "Constant", "Cosecantf", "Cosf", "Cotanf", "Derivativef", "Divf",
"Dividesf", "Eif", "Equalsf", "Erfcf", "Erff", "Erfif", "ExistsUniquef", "Existsf", "Factorialf", "Floorf", "Forallf", "Gcdf",
"GreaterOrEqualf", "Greaterf", "Impliesf", "IncompleteGammaf", "Integralf", "Iversonf", "Lambda", "LambertWf", "Lcmf", "LessOrEqualf",
"Lessf", "Lif", "Limitf", "Logf", "Matrix", "Maxf", "Maximumf", "Minf", "Minimumf", "Minusf", "Modf", "Mulf", "Notf", "Number+Complex",
"Number+Integer", "Number+Rational", "Number+Real", "Orf", "Phif", "Piecewise", "Polygammaf", "Powf", "Primef", "Productf", "Providedf",
"Roundf", "Secantf", "Set+ConditionalSet", "Set+FiniteSet", "Set+IndexedIntersectionf", "Set+IndexedUnionf", "Set+Inf", "Set+Intersectionf",
"Set+Interval", "Set+Powersetf", "Set+SetMinusf", "Set+SpecialSet+Booleans", "Set+SpecialSet+Complexes", "Set+SpecialSet+Integers",
"Set+SpecialSet+NonNegativeIntegers", "Set+SpecialSet+PositiveIntegers", "Set+SpecialSet+Primes", "Set+SpecialSet+Rationals",
"Set+SpecialSet+Reals", "Set+Subsetf", "Set+Unionf", "Shif", "Sif", "Signumf", "Sinf", "SumOverSetf", "Sumf", "Summationf", "Tanf",
"Valuationf", "Variable", "Xorf"
];
private static Entity Parse(string text)
{
using var _ = MathS.Settings.ExplicitParsingOnly.Set(true);
@@ -81,20 +127,20 @@ public sealed class AngouriMathBehaviorTests
}
[Test]
public void DowncastingTurnsTinyValuesIntoZero()
public void DowncastingTurnsTinyLiteralsIntoZero()
{
// The Boltzmann constant at 300 K, the energy of a photon of 500 nm, and e^-100:
using (Assert.EnterMultipleScope())
{
Assert.That(MathS.Settings.DowncastingEnabled.Value, Is.True, "AngouriMath downcasts by default.");
Assert.That(DecimalOf("1.380649e-23 * 300", 30, 20), Is.EqualTo("0"), "Downcasting takes a tiny value for the integer 0, so NumericEvaluator.EvaluateAt does without it.");
Assert.That(DecimalOf("1.380649e-23 * 300", 30, 20), Is.EqualTo("0"), "Downcasting reads a literal below the precision as the integer 0, so NumericEvaluator.EvaluateAt does without it.");
Assert.That(DecimalOf("6.62607015e-34 * 299792458 / 500e-9", 40, 20), Is.EqualTo("0"));
Assert.That(DecimalOf("e^(-100)", 60, 20), Is.EqualTo("0"), "More digits only lower the bound below which a value vanishes.");
Assert.That(DecimalOf("e^(-100)", 60, 20), Is.EqualTo("3.7200759760208359630E-44"), "Since 2.7.0, a computed value keeps its digits; until then, it vanished below the precision.");
using var withoutDowncasting = MathS.Settings.DowncastingEnabled.Set(false);
Assert.That(DecimalOf("1.380649e-23 * 300", 30, 20), Is.EqualTo("4.14194700E-21"));
Assert.That(DecimalOf("6.62607015e-34 * 299792458 / 500e-9", 30, 20), Is.EqualTo("3.97289171430E-19"), "500e-9 is read as the fraction 1/2000000, and dividing by it rounds to 30 decimal places, see below.");
Assert.That(DecimalOf("6.62607015e-34 * 299792458 / 500e-9", 60, 20), Is.EqualTo("3.9728917142978574000E-19"));
Assert.That(DecimalOf("6.62607015e-34 * 299792458 / 500e-9", 30, 20), Is.EqualTo("3.9728917142978574E-19"), "500e-9 is read as the fraction 1/2000000, and since 2.7.0, dividing by it keeps the digits, see below.");
Assert.That(DecimalOf("6.62607015e-34 * 299792458 / 500e-9", 60, 20), Is.EqualTo("3.9728917142978574E-19"));
Assert.That(DecimalOf("e^(-100)", 30, 20), Is.EqualTo("3.7200759760208359630E-44"));
}
}
@@ -106,24 +152,24 @@ public sealed class AngouriMathBehaviorTests
{
Assert.That(Parse("1e-60"), Is.EqualTo(Entity.Number.Integer.Create(0)), "A literal below about 1e-50 is read as 0, so MathExpressionReader parses without downcasting.");
Assert.That(Parse("6.62607015e-34"), Is.TypeOf<Entity.Number.Real>(), "Unlike 0.1, a literal with a long denominator stays an inexact decimal.");
Assert.That(Parse("1 + 1e-40").InnerSimplified, Is.EqualTo(Entity.Number.Integer.Create(1)), "Simplifying drops an inexact decimal from a sum, so MathExpressionReader turns every literal into its fraction.");
Assert.That(Parse("1 + 1e-40").InnerSimplified.ToString(), Is.EqualTo("1 + 1E-40"), "Since 2.7.0, simplifying keeps an inexact decimal in a sum; until then, it dropped it.");
Assert.That(Entity.Number.Rational.Create(EInteger.One, EInteger.FromInt32(10).Pow(200)).EDecimal.IsZero, Is.True, "A fraction converts to a fixed number of decimal places, so NumericEvaluator converts an exact value itself.");
Assert.That(Parse("pi/10^1500").InnerSimplified, Is.EqualTo(Entity.Number.Integer.Create(0)), "Simplifying takes a value below about 1e-1000 for 0, so NumericEvaluator checks an exact 0 numerically.");
Assert.That(Parse("pi/10^1000").InnerSimplified, Is.TypeOf<Entity.Divf>());
// Where it evaluates a function numerically, the bound lies near the precision instead:
// Until 2.7.0, where it evaluated a function numerically, the bound lay near the precision instead:
using var lowerPrecision = MathS.Settings.DecimalPrecisionContext.Set(EContext.ForPrecision(50));
Assert.That(MathS.FromString("132521403/200000000000000000000000000000000000000000 * sin(61/100)", useCache: false).InnerSimplified, Is.EqualTo(Entity.Number.Integer.Create(0)), "So NumericCheck evaluates an exact 0 numerically.");
Assert.That(MathS.FromString("132521403/200000000000000000000000000000000000000000 * sin(61/100)", useCache: false).InnerSimplified, Is.TypeOf<Entity.Mulf>(), "A product is no longer taken for 0; NumericCheck still evaluates an exact 0 numerically.");
}
}
[Test]
public void WithoutDowncastingAQuotientOfIntegersIsRoundedToDecimalPlaces()
public void WithoutDowncastingAQuotientOfIntegersKeepsItsDigits()
{
using var withoutDowncasting = MathS.Settings.DowncastingEnabled.Set(false);
using (Assert.EnterMultipleScope())
{
Assert.That(DecimalOf("3/10^50 * 7", 30, 20), Is.EqualTo("0E-30"), "At 30 digits, the quotient keeps 30 decimal places, so NumericEvaluator.EvaluateAt adds the leading zeros of the smallest fraction to the precision.");
Assert.That(DecimalOf("3/10^50 * 7", 30, 20), Is.EqualTo("2.1E-49"), "Since 2.7.0, the quotient keeps its digits at 30 digits; until then, it kept 30 decimal places, which is why NumericEvaluator.EvaluateAt adds the leading zeros of the smallest fraction to the precision.");
Assert.That(DecimalOf("3/10^50 * 7", 80, 20), Is.EqualTo("2.1000000000000000000E-49"));
Assert.That(DecimalOf("2^(-200)", 30, 20), Is.EqualTo("6.2230152778611417071E-61"), "A power keeps its significant digits.");
}
@@ -182,6 +228,7 @@ public sealed class AngouriMathBehaviorTests
Assert.That(Parse("integral(x^3/(e^x-1), x, 0, +oo)"), Is.TypeOf<Entity.Integralf>());
Assert.That(Parse("limit(sin(x)/x, x, 0)"), Is.TypeOf<Entity.Limitf>());
Assert.That(Parse("+oo"), Is.TypeOf<Entity.Number.Real>());
Assert.That(Parse("x²").ToString(), Is.EqualTo("x ^ 2"), "Since 2.8.0, a superscript is a power, also under explicit parsing.");
}
}
@@ -204,14 +251,42 @@ public sealed class AngouriMathBehaviorTests
using (Assert.EnterMultipleScope())
{
// Under explicit parsing, a character the lexer drops can leave two operands side by side, as in 2·3:
foreach (var text in new[] { "2 + * 3", "(2 + 3", "", "√2", "x²", "2·3", "1,5", "2**3", "|x|", "\\frac{1}{2}" })
foreach (var text in new[] { "2 + * 3", "(2 + 3", "", "√2", "2·3", "1,5", "2**3", "|x|", "\\frac{1}{2}" })
Assert.That(() => Parse(text), Throws.InstanceOf<ParseException>(), text);
Assert.Throws<FunctionArgumentCountException>(() => Parse("sin(1, 2)"));
Assert.Throws<FunctionArgumentCountException>(() => Parse("integral(x^2, x, 2)"), "An integral has two or four arguments.");
Assert.Throws<UnrecognizedFunctionParseException>(() => Parse("factorize(360)"), "Since 2.8.0, some names are refused with a message which names AngouriMath, the C# API, and functions the tools do not support.");
Assert.Throws<UnrecognizedFunctionParseException>(() => Parse("trunc(2.5)"));
}
}
[Test]
public void EveryFunctionAndOperatorOfTheParserIsDecidedOn()
{
var tokens = ParserVocabulary.Tokens();
var functions = ParserVocabulary.FunctionNames();
const string DECISION = "A new token of the parser needs a decision: either MathExpressionReader refuses it, or the tools support it, with a guard in MathGuards where it computes without checking the cancellation token. AngouriMath computes some functions while it parses, so a refusal by the kind of node comes too late for them.";
using (Assert.EnterMultipleScope())
{
Assert.That(functions.Except(MathExpressionReader.UNSUPPORTED_FUNCTIONS).Order(StringComparer.Ordinal), Is.EqualTo(FUNCTIONS_PASSED_ON), DECISION);
Assert.That(tokens.Where(token => !ParserVocabulary.IsFunction(token)).Order(StringComparer.Ordinal), Is.EqualTo(OPERATORS), DECISION);
Assert.That(MathExpressionReader.UNSUPPORTED_FUNCTIONS.Except(functions), Is.Empty, "MathExpressionReader refuses only names the parser reads as a function.");
}
}
[Test]
public void EveryKindOfNodeIsDecidedOn()
{
var passedOn = typeof(Entity).Assembly.GetTypes()
.Where(type => type.IsSubclassOf(typeof(Entity)) && !type.IsAbstract && !MathExpressionReader.UNSUPPORTED_NODE_TYPES.Contains(type))
.Select(type => type.FullName!.Replace("AngouriMath.Entity+", string.Empty, StringComparison.Ordinal))
.Order(StringComparer.Ordinal);
Assert.That(passedOn, Is.EqualTo(NODE_TYPES_PASSED_ON), "A new kind of node needs a decision: either MathExpressionReader refuses it, or the tools support it, with a guard in MathGuards where it computes without checking the cancellation token.");
}
[Test]
public void AParseExceptionNamesLineAndColumn()
{
@@ -374,7 +449,10 @@ public sealed class AngouriMathBehaviorTests
Assert.That(Parse("x^2 + 1 = 0").Solve(X).ToString(), Is.EqualTo("{ i, -i }"), "The codomain does not restrict the solutions.");
Assert.That(Parse("x^2 - 2 = 0").Solve(X).ToString(), Is.EqualTo("{ sqrt(2), -sqrt(2) }"), "The solutions stay exact.");
Assert.That(Parse("sin(x) = 1/2").Solve(X).ToString(), Is.EqualTo("{ pi / 6 + 2 * pi * n_1, pi - pi / 6 + 2 * pi * n_1 }"), "n_1 stands for any integer.");
Assert.That(Parse("sin(x) = 1/2").Solve(X), Is.TypeOf<Entity.Set.IndexedUnionf>(), "Since 2.8.0, infinitely many solutions are a family, see MathSolutions.");
Assert.That(Parse("sin(x) = 1/2").Solve(X).ToString(), Is.EqualTo("union({ pi / 6 + 2 * pi * n, pi - pi / 6 + 2 * pi * n }, n in ZZ)"));
Assert.That(Parse("sin(x) = 1/2").Solve(X).FreeVariables.Select(variable => variable.Name), Has.No.Member("n"), "The family binds its index.");
Assert.That(Parse("e^x = 2").Solve(X).ToString(), Is.EqualTo("union({ ln(2) + 2 * pi * i * n }, n in ZZ)"), "An exponential equation has all its complex solutions; the one for n = 0 is the real one.");
Assert.That(Parse("x^2 < 4").Solve(X), Is.TypeOf<Entity.Set.Interval>());
Assert.That(Parse("x + 1 = x").Solve(X).ToString(), Is.EqualTo("{ }"));
Assert.Throws<SolveRequiresStatementException>(() => Parse("x^2 - 4").Solve(X));
@@ -388,7 +466,7 @@ public sealed class AngouriMathBehaviorTests
using (Assert.EnterMultipleScope())
{
Assert.That(withNewton.Count, Is.EqualTo(5));
Assert.That(withNewton.All(root => root is Entity.Number.Complex { IsExact: false }), "Newton's roots are doubles, printed with every binary digit.");
Assert.That(withNewton.All(root => root is Entity.Number.Complex { IsExact: false }), "Since 2.7.0, the Durand-Kerner iteration gives every root of such a polynomial as a decimal. It never checks the cancellation token, which is one more reason for the tools to switch Newton's method off.");
using (MathS.Settings.AllowNewton.Set(false))
Assert.That(Parse("x^5 + 3*x + 1 = 0").Solve(X), Is.TypeOf<Entity.Set.ConditionalSet>());
@@ -400,15 +478,19 @@ public sealed class AngouriMathBehaviorTests
[Test]
public void SolveHonorsTheCancellationTokenOfItsThread()
{
// Since 2.7.0, nothing without Newton's method takes long enough to cancel it midway in a test, so the token is cancelled from the start:
var task = Task.Run(() =>
{
using var source = new CancellationTokenSource(TimeSpan.FromMilliseconds(200));
var equation = Parse("x^2 - 3*x = 4");
using var source = new CancellationTokenSource();
source.Cancel();
MathS.Multithreading.SetLocalCancellationToken(source.Token);
return Parse("x^20 + x + 1 = 0").Solve(X);
using var withoutNewton = MathS.Settings.AllowNewton.Set(false);
return equation.Solve(X);
});
var exception = Assert.Throws<AggregateException>(() => task.Wait(TimeSpan.FromSeconds(10)))!;
Assert.That(exception.InnerException, Is.InstanceOf<OperationCanceledException>(), "Without the token, this takes about 1.6 seconds.");
Assert.That(exception.InnerException, Is.InstanceOf<OperationCanceledException>(), "MathComputationService stops a computation through this token.");
}
[Test]
@@ -122,7 +122,7 @@ public sealed class CalculateToolTests
var simplifiedToZero = Calculate("1e-2000 * pi");
using (Assert.EnterMultipleScope())
{
Assert.That(RelativeError(quotient, "3.14159265358979323846264e-200"), Is.LessThan(1e-19), "AngouriMath rounds a quotient to decimal places, so the precision grows until the value shows.");
Assert.That(RelativeError(quotient, "3.14159265358979323846264e-200"), Is.LessThan(1e-19), "Up to version 2.6.0, AngouriMath rounded a quotient to decimal places, so the precision grows until the value shows.");
Assert.That(simplifiedToZero.ContainsKey("exact"), Is.False, "AngouriMath simplifies the value to 0, see AngouriMathBehaviorTests.DowncastingWhileParsingLosesTinyLiterals.");
Assert.That(RelativeError(simplifiedToZero, "3.14159265358979323846264e-2000"), Is.LessThan(1e-19));
Assert.That(Text(photon, "decimal"), Is.EqualTo("3.9728917142978574e-19"));
@@ -240,6 +240,32 @@ public sealed class CalculateToolTests
}
}
[Test]
public void ComputesTheSpecialFunctionsWhichSolvingAndIntegratingReturn()
{
// The references are those of Python's decimal module:
using (Assert.EnterMultipleScope())
{
Assert.That(RelativeError(Calculate("lambertw(0, 2)"), "0.85260550201372549134647241469531746689845330015140"), Is.LessThan(1e-19), "W(2) solves w * e^w = 2.");
Assert.That(RelativeError(Calculate("productlog(2)"), "0.85260550201372549134647241469531746689845330015140"), Is.LessThan(1e-19));
Assert.That(RelativeError(Calculate("gamma(2, 1)"), "0.73575888234288464319104754032292173489162226206354"), Is.LessThan(1e-19), "gamma(2, 1) is 2/e.");
Assert.That(RelativeError(Calculate("polygamma(1, 1)"), "1.64493406684822643647241516664602518921894990120680"), Is.LessThan(1e-19), "polygamma(1, 1) is pi^2/6.");
Assert.That(RelativeError(Calculate("integral(lambertw(0, x), x, 0, 1)"), "0.33036612476168058323"), Is.LessThan(1e-12), "The integrand compiles; the integral is W(1) - 2 + 1/W(1).");
Assert.That(Refusal("polygamma(101, 2)"), Does.EndWith("so the order is limited to 100."));
Assert.That(Refusal("gamma(1/2, 10^4)"), Does.EndWith("so the absolute value of z is limited to 1,000."));
}
}
[Test]
public void RefusesAnIntegrandWithoutValuesPointByPointInItsOwnWords()
{
using (Assert.EnterMultipleScope())
{
foreach (var integral in new[] { "integral(gamma(2, x), x, 0, 1)", "integral(derivative(sin(x)*x, x), x, 0, 1)", "integral(limit(sin(x*t)/t, t, 0), x, 0, 1)" })
Assert.That(Refusal(integral), Does.EndWith("cannot be evaluated point by point, which a numerical integration needs, e.g., since it holds gamma(a, z), a derivative, or a limit."), integral);
}
}
[Test]
public void RefusesAnIntegralItCannotIntegrate()
{
@@ -4,6 +4,7 @@ using System.Text.Json.Nodes;
using AIStudio.Tools.Mathematics;
using AIStudio.Tools.ToolCallingSystem.ToolCallingImplementations.Mathematics;
using AngouriMath;
using AngouriMath.Core;
using Microsoft.Extensions.Logging.Abstractions;
@@ -34,6 +35,21 @@ public sealed class ComputeSymbolicallyToolTests
private static string RequestRefusal(string json) => Assert.Throws<ArgumentException>(() => ComputeSymbolicallyTool.ReadRequest(Arguments(json)))!.Message;
/// <summary>
/// Writes the solutions of an equation in x as the tool does, for a set of solutions given as text.
/// </summary>
private static Task<JsonObject> DescribeSolutions(string equation, string solutions) => SERVICE.ComputeAsync(_ =>
{
var statement = MathExpressionReader.Read(equation, "expression");
var json = new JsonObject();
var issues = new List<string>();
ComputeSymbolicallyTool.Solutions(json, issues, statement, statement, MathS.Var("x"), MathExpressionReader.Read(solutions, "solutions"));
json["issues"] = new JsonArray([..issues.Select(issue => JsonValue.Create(issue))]);
return json;
});
private static JsonNode Member(JsonObject json, int index) => json["solutions"]![index]!;
[Test]
public async Task SimplifiesAndStatesTheCondition()
{
@@ -155,13 +171,140 @@ public sealed class ComputeSymbolicallyToolTests
Assert.That(Text(quadratic, "verification"), Is.EqualTo("passed"));
Assert.That(complex["solutions"]![0]!["real"]!.GetValue<bool>(), Is.False);
Assert.That(Text(complex, "verification"), Is.EqualTo("passed"));
Assert.That(Text(periodic, "verification"), Is.EqualTo("passed"), "n_1 takes integer values in the check.");
Assert.That(Issues(periodic), Has.Member("n_1 stands for any integer."));
Assert.That(Text(periodic, "verification"), Is.EqualTo("passed"), "The index takes integer values in the check.");
Assert.That(Member(periodic, 0)["holds_for"]!.GetValue<string>(), Is.EqualTo("every integer n"));
Assert.That(Member(periodic, 1)["at_index_0"]!["value"]!.GetValue<string>(), Is.EqualTo("5/6 * pi"));
Assert.That(Issues(withoutEquals), Has.Member("The expression has no '=', so it was solved for expression = 0."));
Assert.That(withoutEquals["solutions"]!.AsArray(), Has.Count.EqualTo(2));
}
}
[Test]
public async Task ListsAndChecksTheMembersOfAFamilyOfSolutions()
{
var periodic = await DescribeSolutions("sin(x) = 1/2", "union({ pi/6 + 2*pi*n, pi - pi/6 + 2*pi*n }, n in ZZ)");
var exponential = await DescribeSolutions("2^x = 5", "union({ log(2, 5) + 2*pi*i*n/ln(2) }, n in ZZ)");
var wrong = await DescribeSolutions("sin(x) = 1/2", "union({ pi/5 + 2*pi*n }, n in ZZ)");
using (Assert.EnterMultipleScope())
{
Assert.That(periodic["solutions"]!.AsArray(), Has.Count.EqualTo(2));
Assert.That(Member(periodic, 0)["holds_for"]!.GetValue<string>(), Is.EqualTo("every integer n"));
Assert.That(Member(periodic, 0)["at_index_0"]!["value"]!.GetValue<string>(), Is.EqualTo("pi / 6"));
Assert.That(Member(periodic, 0)["at_index_0"]!["decimal"]!.GetValue<string>(), Does.StartWith("0.52359877559"));
Assert.That(Member(periodic, 0)["at_index_0"]!["real"]!.GetValue<bool>(), Is.True);
Assert.That(Member(periodic, 0).AsObject().ContainsKey("decimal"), Is.False, "A member with an index has no single value.");
Assert.That(Text(periodic, "verification"), Is.EqualTo("passed"), "The index takes integer values in the check.");
Assert.That(periodic["complete"]!.GetValue<bool>(), Is.True);
Assert.That(Member(exponential, 0)["at_index_0"]!["decimal"]!.GetValue<string>(), Does.StartWith("2.32192809488"), "The solution for the index 0 is the real one, which a model needs most.");
Assert.That(Text(exponential, "verification"), Is.EqualTo("passed"));
Assert.That(Text(wrong, "verification"), Is.EqualTo("failed"));
}
}
[Test]
public async Task GivesTheRealSolutionOfAnExponentialEquation()
{
// The decimals are those of Python's decimal module, to 15 significant digits:
var power = await Compute(SymbolicOperation.SOLVE, "2^x = 5");
var doubling = await Compute(SymbolicOperation.SOLVE, "1.05^x = 2");
var lambert = await Compute(SymbolicOperation.SOLVE, "x*e^x = 2");
using (Assert.EnterMultipleScope())
{
Assert.That(Member(power, 0)["at_index_0"]!["decimal"]!.GetValue<string>(), Is.EqualTo("2.32192809488736"));
Assert.That(Text(power, "verification"), Is.EqualTo("passed"));
Assert.That(Member(doubling, 0)["at_index_0"]!["decimal"]!.GetValue<string>(), Is.EqualTo("14.2066990828905"), "The years in which 5 % interest doubles a sum.");
Assert.That(Member(doubling, 0)["at_index_0"]!["real"]!.GetValue<bool>(), Is.True);
Assert.That(Member(lambert, 0)["at_index_0"]!["value"]!.GetValue<string>(), Is.EqualTo("lambertw(2)"));
Assert.That(Member(lambert, 0)["at_index_0"]!["decimal"]!.GetValue<string>(), Is.EqualTo("0.852605502013725"));
Assert.That(Text(lambert, "verification"), Is.EqualTo("passed"));
}
}
[Test]
public async Task GivesSolutionsCalculateTakes()
{
foreach (var equation in new[] { "2^x = 5", "x*e^x = 2", "sin(x) = 1/2" })
{
var solution = Member(await Compute(SymbolicOperation.SOLVE, equation), 0)["at_index_0"]!;
var value = await SERVICE.ComputeAsync(token => CalculateTool.Calculate(solution["value"]!.GetValue<string>(), 15, token));
Assert.That(value["decimal"]!.GetValue<string>(), Is.EqualTo(solution["decimal"]!.GetValue<string>()), equation);
}
}
[Test]
public async Task ChecksAnAntiderivativeFarLargerThanTheIntegrand()
{
// The antiderivative -gamma(41, x) is about 40!, its derivative x^40 * e^(-x) about 1e-9:
var integrated = await Compute(SymbolicOperation.INTEGRATE, "x^40*e^(-x)");
using (Assert.EnterMultipleScope())
{
Assert.That(Text(integrated, "result"), Is.EqualTo("-gamma(41, x) + C"));
Assert.That(Text(integrated, "verification"), Is.EqualTo("passed"));
}
}
[Test]
public async Task ChecksNoSamplePointWhichCouldNotBeStopped()
{
// At x = 0.61, z is 6,100, the factorial that of 610,000, and the power a fraction of 378,000 digits; each
// would take seconds or minutes without a way to stop it:
var incompleteGamma = await Compute(SymbolicOperation.SIMPLIFY, "gamma(1/2, 10000*x)");
var factorial = await Compute(SymbolicOperation.SIMPLIFY, "(10^6*x)!");
var derivative = await Compute(SymbolicOperation.DIFFERENTIATE, "(10^6*x)!", "x");
var power = await Compute(SymbolicOperation.SIMPLIFY, "x^100000 + 1");
// The terms of the expansion each have a few hundred digits, which is no reason to leave a point out:
var expansion = await Compute(SymbolicOperation.EXPAND, "(x + 1)^200");
var smallerFactorial = await Compute(SymbolicOperation.SIMPLIFY, "(1000*x)!");
using (Assert.EnterMultipleScope())
{
Assert.That(Text(incompleteGamma, "verification"), Is.EqualTo("not_possible"));
Assert.That(Text(factorial, "verification"), Is.EqualTo("not_possible"));
Assert.That(Text(derivative, "verification"), Is.EqualTo("not_possible"));
Assert.That(Text(power, "verification"), Is.EqualTo("not_possible"));
Assert.That(Text(expansion, "verification"), Is.EqualTo("passed"));
Assert.That(Text(smallerFactorial, "verification"), Is.EqualTo("passed"));
}
}
[Test]
public async Task AnswersWhatRanPastTheBudgetBefore()
{
// Each of these took the whole budget of 10 seconds with version 2.6.0:
var mixedBases = await Compute(SymbolicOperation.SOLVE, "(-2)^x + 4^x = 0");
var quintic = await Compute(SymbolicOperation.SOLVE, "x^5 + x - sqrt(2) = 0");
using (Assert.EnterMultipleScope())
{
Assert.That(mixedBases["complete"]!.GetValue<bool>(), Is.True);
Assert.That(Text(mixedBases, "verification"), Is.EqualTo("passed"));
Assert.That(quintic["complete"]!.GetValue<bool>(), Is.False);
}
}
[Test]
public async Task TakesFamiliesOfSolutionsApart()
{
var withoutZero = await DescribeSolutions("sin(x)/x = 0", "union({ pi*n }, n in ZZ \\ { 0 })");
var nested = await DescribeSolutions("e^(sin(x)) = 1", "union(union({ arcsin(2*pi*i*n) + 2*pi*m, pi - arcsin(2*pi*i*n) + 2*pi*m }, m in ZZ), n in ZZ)");
var joined = await DescribeSolutions("sin(x)*(x - 7) = 0", "{ 7 } \\/ union({ pi*n }, n in ZZ)");
var unsolved = await DescribeSolutions("sin(x) = x^5", "{ x : sin(x) = x^5 } \\/ union({ pi*n }, n in ZZ)");
using (Assert.EnterMultipleScope())
{
Assert.That(Member(withoutZero, 0)["holds_for"]!.GetValue<string>(), Does.StartWith("every n in ZZ"));
Assert.That(Member(withoutZero, 0).AsObject().ContainsKey("at_index_0"), Is.False, "0 is not among the values of the index.");
Assert.That(Text(withoutZero, "verification"), Is.EqualTo("passed"), "At 0, the index would take a value without a solution.");
Assert.That(Member(nested, 0)["holds_for"]!.GetValue<string>(), Is.EqualTo("every integer n and every integer m"), "The outer index comes first.");
Assert.That(Member(nested, 0)["at_index_0"]!["value"]!.GetValue<string>(), Is.EqualTo("0"));
Assert.That(Text(nested, "verification"), Is.EqualTo("passed"));
Assert.That(joined["solutions"]!.AsArray(), Has.Count.EqualTo(2));
Assert.That(Member(joined, 0).AsObject().ContainsKey("holds_for"), Is.False);
Assert.That(Member(joined, 1)["holds_for"]!.GetValue<string>(), Is.EqualTo("every integer n"));
Assert.That(Text(joined, "verification"), Is.EqualTo("passed"));
Assert.That(unsolved["complete"]!.GetValue<bool>(), Is.False, "A part without a closed form leaves the solutions incomplete.");
Assert.That(unsolved.ContainsKey("solutions"), Is.False);
}
}
[Test]
public async Task WorksWithSumsAndDivisors()
{
@@ -1,6 +1,9 @@
using System.Reflection;
using AIStudio.Tools.Mathematics;
using AngouriMath;
using AngouriMath.Core.Exceptions;
using Microsoft.Extensions.Logging.Abstractions;
@@ -104,6 +107,15 @@ public sealed class MathComputationServiceTests
Assert.That(() => service.ComputeAsync(SpinUntilCanceled, request.Token), Throws.InstanceOf<OperationCanceledException>());
}
[Test]
public async Task ABugOfAngouriMathBecomesAMessageWithoutTheLibrary()
{
var service = CreateService();
var bug = (Exception)Activator.CreateInstance(typeof(AngouriBugException), BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, ["please report about it to the official repository of AngouriMath"], null)!;
var exception = (await Assert.ThrowsAsync<MathComputationException>(() => service.ComputeAsync<int>(_ => throw bug)))!;
Assert.That(exception.Message, Is.EqualTo("The tool ran into an error of its own with this expression and could not compute it."));
}
[Test]
public async Task AnExceptionOfAngouriMathBecomesAMessageAndFreesTheSlot()
{
@@ -112,7 +124,7 @@ public sealed class MathComputationServiceTests
using (Assert.EnterMultipleScope())
{
Assert.That(exception.Message, Does.StartWith("The tool could not compute this:`x + 1` evaluates to `x + 1`"));
Assert.That(exception.Message, Does.StartWith("The tool could not compute this: `x + 1` evaluates to `x + 1`"));
Assert.That(await service.ComputeAsync(_ => 4), Is.EqualTo(4));
}
}
@@ -9,6 +9,19 @@ public sealed class MathExpressionReaderTests
{
private static string Refusal(string text, string argumentName = "expression") => Assert.Throws<MathComputationException>(() => MathExpressionReader.Read(text, argumentName))!.Message;
private static string? RefusalOrNull(string text)
{
try
{
MathExpressionReader.Read(text, "expression");
return null;
}
catch (MathComputationException exception)
{
return exception.Message;
}
}
[Test]
public void ReadsTheSyntaxOfTheTools()
{
@@ -38,6 +51,62 @@ public sealed class MathExpressionReaderTests
}
}
[Test]
public void ReadsTheFunctionsTheToolsReturn()
{
using (Assert.EnterMultipleScope())
{
Assert.That(MathExpressionReader.Read("lambertw(0, 2)", "expression"), Is.TypeOf<Entity.LambertWf>());
Assert.That(MathExpressionReader.Read("productlog(2)", "expression"), Is.TypeOf<Entity.LambertWf>());
Assert.That(MathExpressionReader.Read("gamma(2, 1)", "expression"), Is.TypeOf<Entity.IncompleteGammaf>());
Assert.That(MathExpressionReader.Read("polygamma(1, 1)", "expression"), Is.TypeOf<Entity.Polygammaf>());
Assert.That(MathExpressionReader.Read("digamma(1)", "expression"), Is.TypeOf<Entity.Polygammaf>());
Assert.That(MathExpressionReader.Read("real + zeta_2", "expression"), Is.TypeOf<Entity.Sumf>(), "A variable may carry the name of a function the tools do not support.");
}
}
[Test]
public void RefusesTheFunctionsTheToolsDoNotSupport()
{
using (Assert.EnterMultipleScope())
{
foreach (var name in MathExpressionReader.UNSUPPORTED_FUNCTIONS)
Assert.That(Refusal($"1 + {name}(2)"), Is.EqualTo($"Argument 'expression' uses the function '{name}', which the tool does not support."));
Assert.That(Refusal("det([[1, 2], [3, 4]])", "lower_bound"), Is.EqualTo("Argument 'lower_bound' uses the function 'det', which the tool does not support."), "AngouriMath computes the determinant of a matrix written out while it parses.");
Assert.That(Refusal("n!!"), Is.EqualTo("Argument 'expression' contains 'n!!', which the tool does not support."));
Assert.That(Refusal("A[1, 2] + 1"), Is.EqualTo("Argument 'expression' contains 'A[1, 2]', which the tool does not support."));
Assert.That(Refusal("product(k, k in { 1, 2, 3 })"), Is.EqualTo("Argument 'expression' contains 'product(k, k in { 1, 2, 3 })', which the tool does not support."));
}
}
[Test]
public void NamesAFunctionTheParserRefuses()
{
using (Assert.EnterMultipleScope())
{
Assert.That(Refusal("trunc(2.5)"), Is.EqualTo("Argument 'expression' uses the function 'trunc', which the tool does not support."));
Assert.That(Refusal("1 + arcsinh(1)"), Is.EqualTo("Argument 'expression' uses the function 'arcsinh', which the tool does not support."));
Assert.That(Refusal("φ(12)"), Is.EqualTo("Argument 'expression' uses the function 'φ', which the tool does not support."));
Assert.That(Refusal("x!!!"), Is.EqualTo("Argument 'expression' uses a function or an operator which the tool does not support."));
}
}
[Test]
public void NoRefusalNamesTheLibrary()
{
var texts = ParserVocabulary.FunctionNames().SelectMany(name => new[] { $"{name}(2)", $"{name}(2, 3)", $"{name}(x)" }).Concat(["x!!!", "φ(12)", "ϕ(12)", "trunc(2.5)", "arcsinh(1)"]);
using (Assert.EnterMultipleScope())
{
foreach (var text in texts)
{
var refusal = RefusalOrNull(text);
if (refusal is not null)
Assert.That(refusal, Does.Not.Contain("AngouriMath").And.Not.Contain("C#").And.Not.Contain(".Evaled").And.Not.Contain("Simplify()").And.Not.Contain("MathS"), text);
}
}
}
[Test]
public void NamesTheMissingOperator()
{
+34 -1
View File
@@ -43,12 +43,45 @@ public sealed class MathGuardsTests
}
}
[Test]
public void RefusesSpecialFunctionsBeyondTheirLimits()
{
using (Assert.EnterMultipleScope())
{
Assert.That(ExactSizeRefusal("polygamma(101, 2)"), Is.EqualTo("'polygamma(101, 2)' has the order 101. The tool cannot stop the computation of polygamma midway, and its time grows with the order, so the order is limited to 100."));
Assert.That(ExactSizeRefusal("1 + polygamma(10^3, x)"), Does.StartWith("'polygamma(10 ^ 3, x)' has the order 1000."), "The order is a number even when the argument is a variable.");
Assert.That(ExactSizeRefusal("polygamma((10^9)!, 2)"), Does.StartWith("'(10 ^ 9)!' would have about"), "The order is judged before its value is needed.");
Assert.That(ExactSizeRefusal("gamma(1/2, 1001)"), Is.EqualTo("'gamma(1 / 2, 1001)' takes gamma(a, z) at a z of about 1001 in absolute value. The tool cannot stop this computation midway, and its time grows with z, so the absolute value of z is limited to 1,000."));
Assert.That(ExactSizeRefusal("gamma(1/2, 10 + 1000*i)"), Does.Contain("at a z of about 1000.05 in absolute value"));
Assert.That(ExactSizeRefusal("gamma(401/2, 2)"), Is.EqualTo("'gamma(401 / 2, 2)' takes gamma(a, z) for a = 401/2. The tool cannot stop this computation midway, and its time grows with z, the more so when a is negative or not real, so a is limited to the real numbers from -20 to 200."));
Assert.That(ExactSizeRefusal("gamma(-41/2, 2)"), Does.Contain("for a = -41/2."));
Assert.That(ExactSizeRefusal("gamma(1 + i, x)"), Does.Contain("for a = 1 + i."), "The parameter is a number even when z is a variable.");
Assert.That(() => MathGuards.CheckValueAtPoint(Read("2 * gamma(1/2, 3001/3)")), Throws.InstanceOf<MathComputationException>());
}
}
[Test]
public void RefusesAtAPointWhatAValueMakesTooLarge()
{
using (Assert.EnterMultipleScope())
{
// (10^6 * x)! and x^100000 at x = 0.61, as at a sample point of the checks:
Assert.That(Assert.Throws<MathComputationException>(() => MathGuards.CheckValueAtPoint(Read("1 + (10^6 * 61/100)!")))!.Message, Does.StartWith("'(10 ^ 6 * 61 / 100)!' would have about 3,"));
Assert.That(Assert.Throws<MathComputationException>(() => MathGuards.CheckValueAtPoint(Read("(61/100)^100000")))!.Message, Does.StartWith("'(61 / 100) ^ 100000' would have about 378,"));
Assert.That(() => MathGuards.CheckValueAtPoint(Read("polygamma(1000 * 61/100, 2)")), Throws.InstanceOf<MathComputationException>());
// The terms of a sum count one by one, unlike for CheckExactSize:
Assert.DoesNotThrow(() => MathGuards.CheckValueAtPoint(Read("10^15000 + 3 * 10^19000 + (1000 * 223/100)!")));
Assert.That(ExactSizeRefusal("10^15000 + 3 * 10^19000"), Does.Contain("would have about 34,"));
}
}
[Test]
public void LetsThroughWhatIsComputedQuickly()
{
using (Assert.EnterMultipleScope())
{
foreach (var text in new[] { "2^10000", "10^19999", "5000!", "0.5!", "(3!)!", "x^1000000", "2^x", "pi^1000000", "e^(10^6)", "1^(10^100)", "0^(10^100)", "547 / 57576", "integral(x^3/(e^x-1), x, 0, +oo)" })
foreach (var text in new[] { "2^10000", "10^19999", "5000!", "0.5!", "(3!)!", "x^1000000", "2^x", "pi^1000000", "e^(10^6)", "1^(10^100)", "0^(10^100)", "547 / 57576", "integral(x^3/(e^x-1), x, 0, +oo)", "polygamma(100, 1/3)", "digamma(10^9)", "polygamma(n, x)", "gamma(200, 1000)", "gamma(-20, -1000)", "gamma(-20, 1000*i)", "gamma(x, 10^3)", "gamma(a, 1/2)", "lambertw(10^6, 2)" })
Assert.DoesNotThrow(() => MathGuards.CheckExactSize(Read(text)), text);
}
}
@@ -9,6 +9,16 @@ public sealed class NumericCheckTests
{
private static NumericCheckOutcome Check(string left, string right) => NumericCheck.AreEqual(MathExpressionReader.Read(left, "left"), MathExpressionReader.Read(right, "right"));
/// <summary>
/// The values an index takes across the sample points.
/// </summary>
private static List<Entity> ValuesOf(SolutionIndex index) => Enumerable.Range(0, 6)
.Select(point => NumericCheck.SampleAssignment(point, [index.Variable], [index]))
.Where(assignment => assignment.ContainsKey(index.Variable))
.Select(assignment => assignment[index.Variable])
.Distinct()
.ToList();
[Test]
public void PassesWhatIsEqual()
{
@@ -93,16 +103,42 @@ public sealed class NumericCheckTests
}
[Test]
public void GivesAnIntegerParameterIntegerValues()
public void ChecksADerivativeOfAFunctionFarLargerThanIt()
{
var parameter = MathS.Var("n_1");
var values = Enumerable.Range(0, 6).Select(point => NumericCheck.SampleAssignment(point, [parameter])[parameter]).Distinct().ToList();
var x = MathS.Var("x");
using (Assert.EnterMultipleScope())
{
Assert.That(values, Is.EquivalentTo(new Entity[] { -1, 0, 1 }));
Assert.That(NumericCheck.IsIntegerParameter(MathS.Var("n_12")), Is.True);
Assert.That(NumericCheck.IsIntegerParameter(MathS.Var("n")), Is.False);
Assert.That(NumericCheck.IsIntegerParameter(MathS.Var("n_x")), Is.False);
Assert.That(NumericCheck.IsDerivativeOf(MathExpressionReader.Read("cos(x)", "derivative"), MathExpressionReader.Read("100! + sin(x)", "function"), x), Is.EqualTo(NumericCheckOutcome.PASSED), "100! has 158 digits, so 60 of them leave nothing of sin(x).");
Assert.That(NumericCheck.IsDerivativeOf(MathExpressionReader.Read("-x^99 * e^(-x)", "derivative"), MathExpressionReader.Read("gamma(100, x)", "function"), x), Is.EqualTo(NumericCheckOutcome.PASSED), "gamma(100, x) is about 99!, and its derivative about 1e-21.");
Assert.That(NumericCheck.IsDerivativeOf(MathExpressionReader.Read("cos(x) + 10^-15", "derivative"), MathExpressionReader.Read("100! + sin(x)", "function"), x), Is.EqualTo(NumericCheckOutcome.FAILED));
Assert.That(NumericCheck.IsDerivativeOf(MathExpressionReader.Read("cos(x)", "derivative"), MathExpressionReader.Read("10^2000 + sin(x)", "function"), x), Is.EqualTo(NumericCheckOutcome.NOT_POSSIBLE), "It would take over 2,000 digits.");
}
}
[Test]
public void GivesAVariableNamedLikeAnIndexNoIntegers()
{
// The index of a family is known by its family, not by its name:
var parameter = MathS.Var("n_1");
var values = Enumerable.Range(0, 6).Select(point => NumericCheck.SampleAssignment(point, [parameter])[parameter]).Distinct().ToList();
Assert.That(values, Has.None.InstanceOf<Entity.Number.Integer>());
}
[Test]
public void GivesAnIndexIntegersOfItsSet()
{
var n = MathS.Var("n");
var integers = new SolutionIndex(n, MathS.Sets.Z);
var withoutZero = new SolutionIndex(n, (Entity.Set)MathExpressionReader.Read("ZZ \\ { 0 }", "set"));
var none = new SolutionIndex(n, (Entity.Set)MathExpressionReader.Read("{ 1/2 }", "set"));
using (Assert.EnterMultipleScope())
{
Assert.That(ValuesOf(integers), Is.EquivalentTo(new Entity[] { -1, 0, 1 }));
Assert.That(ValuesOf(withoutZero), Is.EquivalentTo(new Entity[] { -1, 1, 2 }));
Assert.That(ValuesOf(none), Is.Empty);
Assert.That(NumericCheck.AreEqual(MathExpressionReader.Read("sin(pi/6 + 2*pi*n)", "left"), MathExpressionReader.Read("1/2", "right"), [integers]), Is.EqualTo(NumericCheckOutcome.PASSED));
Assert.That(NumericCheck.AreEqual(MathExpressionReader.Read("sin(pi/6 + pi*n)", "left"), MathExpressionReader.Read("1/2", "right"), [integers]), Is.EqualTo(NumericCheckOutcome.FAILED), "At n = -1 and 1, the sine is -1/2.");
Assert.That(NumericCheck.AreEqual(MathExpressionReader.Read("n", "left"), MathExpressionReader.Read("n", "right"), [none]), Is.EqualTo(NumericCheckOutcome.NOT_POSSIBLE), "An index which takes none of the integers tried leaves no point.");
}
}
@@ -0,0 +1,41 @@
using System.Globalization;
using System.Text.RegularExpressions;
using AngouriMath;
using Antlr4.Runtime;
namespace AIStudio.Tests.Tools.Mathematics;
/// <summary>
/// The tokens of AngouriMath's parser, read from the lexer of the version loaded.
/// </summary>
public static partial class ParserVocabulary
{
/// <summary>
/// Every literal token of the parser without its quotes, such as sin( or !!.
/// </summary>
public static IReadOnlyList<string> Tokens()
{
var vocabulary = (IVocabulary)typeof(Entity).Assembly.GetType("AngouriMath.Core.Antlr.AngouriMathLexer", throwOnError: true)!.GetField("DefaultVocabulary")!.GetValue(null)!;
return [..Enumerable.Range(0, 1000).Select(vocabulary.GetLiteralName).Where(name => name is not null).Select(Unquote)];
}
/// <summary>
/// Whether a token opens the arguments of a function, as sin( does.
/// </summary>
public static bool IsFunction(string token) => token.Length > 1 && token.EndsWith('(');
/// <summary>
/// The names of the functions of the parser, such as sin.
/// </summary>
public static IReadOnlyList<string> FunctionNames() => [..Tokens().Where(IsFunction).Select(token => token[..^1])];
/// <summary>
/// A literal name of the parser without its quotes, with its escapes, such as \u2026, decoded.
/// </summary>
private static string Unquote(string literalName) => UnicodeEscape().Replace(literalName[1..^1], match => ((char)int.Parse(match.Groups["code"].Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture)).ToString());
[GeneratedRegex(@"\\u(?<code>[0-9A-Fa-f]{4})")]
private static partial Regex UnicodeEscape();
}