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 -1
View File
@@ -127,7 +127,7 @@ Code which decides something on behalf of a request — whether the classic RAG
**Area guide:** `app/MindWork AI Studio/Tools/ToolCallingSystem/AGENTS.md`, with how to add, change, or
remove a tool and the rules every tool implementation follows.
**Mathematics.** Code which computes with AngouriMath runs inside `MathComputationService.ComputeAsync` and reads expressions with `MathExpressionReader`, never by calling `MathS` or `Entity` on a thread of its own: the service gives it the stack deep expressions need, the time budget, and the settings the tools rely on, such as explicit parsing. Check exact values and expansions with `MathGuards` first, since AngouriMath ignores the cancellation there. Evaluate a value numerically with `NumericEvaluator.EvaluateAt`, not with `EvalNumerical`: by default, AngouriMath takes tiny values, such as those of physical constants, for 0. Never name AngouriMath in a text the model reads, such as a refusal or an issue; write "the tool" instead. See "Mathematics" in `documentation/Tools.md`.
**Mathematics.** Code which computes with AngouriMath runs inside `MathComputationService.ComputeAsync` and reads expressions with `MathExpressionReader`, never by calling `MathS` or `Entity` on a thread of its own: the service gives it the stack deep expressions need, the time budget, and the settings the tools rely on, such as explicit parsing. Check exact values and expansions with `MathGuards` first, since AngouriMath ignores the cancellation there. Evaluate a value numerically with `NumericEvaluator.EvaluateAt`, not with `EvalNumerical`: by default, AngouriMath downcasts and takes tiny values, such as those of physical constants, for 0 at the precision it reads them with. Never name AngouriMath in a text the model reads, such as a refusal or an issue; write "the tool" instead. See "Mathematics" in `documentation/Tools.md`.
## Model Capabilities
@@ -99,7 +99,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="AngouriMath" Version="2.6.0" />
<PackageReference Include="AngouriMath" Version="2.8.0" />
<PackageReference Include="CodeBeam.MudBlazor.Extensions" Version="9.2.0" />
<PackageReference Include="DocumentFormat.OpenXml" Version="3.5.1" />
<PackageReference Include="HtmlAgilityPack" Version="1.12.4" />
@@ -116,10 +116,16 @@ public sealed class MathComputationService(ILogger<MathComputationService> logge
{
completion.TrySetException(new MathComputationException($"The computation did not finish within {this.BudgetInSeconds} seconds."));
}
catch (AngouriBugException exception)
{
// Its message asks to report the bug to the repository of AngouriMath, which a model cannot do:
logger.LogWarning("AngouriMath ran into a bug of its own: {Message}", exception.Message);
completion.TrySetException(new MathComputationException("The tool ran into an error of its own with this expression and could not compute it."));
}
catch (AngouriMathBaseException exception)
{
logger.LogInformation("AngouriMath could not compute an expression: {Message}", exception.Message);
completion.TrySetException(new MathComputationException($"The tool could not compute this:{exception.Message.Shorten(MAX_MESSAGE_LENGTH)}"));
completion.TrySetException(new MathComputationException($"The tool could not compute this: {exception.Message.Shorten(MAX_MESSAGE_LENGTH)}"));
}
catch (Exception exception)
{
@@ -1,3 +1,4 @@
using System.Collections.Frozen;
using System.Globalization;
using System.Text.RegularExpressions;
@@ -19,20 +20,64 @@ namespace AIStudio.Tools.Mathematics;
/// even with it, a != b is the factorial of a equated to b. This reader refuses such spellings
/// instead of letting a model compute what it did not mean, and states how AngouriMath writes the
/// thing instead. Its parse errors list over a thousand characters of expected tokens; the reader
/// keeps the column and the cause.<br/><br/>
/// keeps the column and the cause. Where AngouriMath refuses a name of its own, its message names
/// the library, its C# API, and functions the tools do not support; the reader keeps the name.<br/><br/>
/// It also refuses the functions which AngouriMath reads since version 2.7.0 or 2.8.0, except those the
/// tools return, see UNSUPPORTED_FUNCTIONS and UNSUPPORTED_NODE_TYPES.<br/><br/>
/// Call it inside a computation of MathComputationService: the parser needs the stack of its thread.
/// </remarks>
public static partial class MathExpressionReader
{
private const int MAX_REASON_LENGTH = 200;
private const int MAX_SHOWN_LENGTH = 120;
/// <summary>
/// The functions which AngouriMath reads since version 2.7.0 or 2.8.0, and which the tools do not support.
/// </summary>
/// <remarks>
/// AngouriMath computes some of them while it parses, such as det, dot, or jacobian of a matrix written
/// out, so nothing of them is left in the expression to refuse afterward. The reader therefore refuses
/// them by name before parsing, also those which AngouriMath refuses itself, such as nextprime, since its
/// messages name the library. lambertw, productlog, polygamma, and digamma stay readable, since solving,
/// integrating, and differentiating return them. AngouriMathBehaviorTests lists every name AngouriMath reads.
/// </remarks>
internal static readonly FrozenSet<string> UNSUPPORTED_FUNCTIONS = new[]
{
"arg", "beta", "catalannumber", "conj", "conjugate", "cross", "curl", "det", "divergence", "divisors", "divisorsigma", "dot",
"doublefactorial", "factorial2", "factorialpower", "factorization", "factorize", "fallingfactorial", "forwarddifference",
"fractionalpart", "gradient", "harmonicnumber", "heaviside", "hessian", "hurwitzzeta", "im", "Im", "imag", "isprime", "jacobian",
"laplacian", "mobius", "moebiusmu", "multinomial", "nextprime", "norm", "partialderivative", "pochhammer", "primefactors", "primenu",
"primeomega", "primepi", "quotient", "re", "Re", "real", "resultant", "riemannzeta", "risingfactorial", "trace", "transpose",
"unitstep", "zeta"
}.ToFrozenSet(StringComparer.Ordinal);
/// <summary>
/// The kinds of nodes which AngouriMath has since version 2.7.0 or 2.8.0, and which the tools do not support.
/// </summary>
/// <remarks>
/// Most of them come from a function of UNSUPPORTED_FUNCTIONS, which the reader refuses by name before.
/// Three come without a name: the double factorial n!!, the entry A[1, 2] of a matrix, and the product
/// over a set, product(f, x in S). LambertWf, IncompleteGammaf, which gamma(a, z) reads into, and
/// Polygammaf stay readable, since solving, integrating, and differentiating return them.
/// </remarks>
internal static readonly FrozenSet<Type> UNSUPPORTED_NODE_TYPES = new[]
{
typeof(Entity.Argf), typeof(Entity.Betaf), typeof(Entity.CatalanNumberf), typeof(Entity.Conjugatef), typeof(Entity.CrossProductf),
typeof(Entity.Determinantf), typeof(Entity.DivisorSigmaf), typeof(Entity.DotProductf), typeof(Entity.DoubleFactorialf),
typeof(Entity.FallingFactorialf), typeof(Entity.HarmonicNumberf), typeof(Entity.Imf), typeof(Entity.MatrixEntryf), typeof(Entity.Mobiusf),
typeof(Entity.Normf), typeof(Entity.PartialDerivativef), typeof(Entity.PrimeFactorizationf), typeof(Entity.Set.PrimeFactorsf),
typeof(Entity.PrimeNuf), typeof(Entity.PrimeOmegaf), typeof(Entity.PrimePif), typeof(Entity.ProductOverSetf), typeof(Entity.Ref),
typeof(Entity.RisingFactorialf), typeof(Entity.Tracef), typeof(Entity.Transposef), typeof(Entity.Zetaf)
}.ToFrozenSet();
/// <summary>
/// Reads an expression, or refuses it.
/// </summary>
/// <param name="text">The expression as the model wrote it.</param>
/// <param name="argumentName">The argument the expression came in, named in every message.</param>
/// <returns>The expression as AngouriMath reads it.</returns>
/// <exception cref="MathComputationException">The expression is empty, too long, uses a spelling AngouriMath reads otherwise, or cannot be read.</exception>
/// <exception cref="MathComputationException">The expression is empty, too long, uses a spelling AngouriMath reads otherwise or a function the tools do not support, or cannot be read.</exception>
public static Entity Read(string text, string argumentName)
{
if (string.IsNullOrWhiteSpace(text))
@@ -51,10 +96,18 @@ public static partial class MathExpressionReader
if (equalsSigns > 1)
throw new MathComputationException($"Argument '{argumentName}' contains {equalsSigns} equals signs, but an expression holds one equation at most. The tool would read a chain of them as several equations joined by 'and'.");
var unsupportedFunction = FunctionNames().Matches(text).Select(match => match.Groups["name"].Value).FirstOrDefault(UNSUPPORTED_FUNCTIONS.Contains);
if (unsupportedFunction is not null)
throw new MathComputationException($"Argument '{argumentName}' uses the function '{unsupportedFunction}', which the tool does not support.");
var expression = Parse(text, argumentName);
if (expression.Vars.Any(variable => variable.Name == "oo"))
throw new MathComputationException($"Argument '{argumentName}' uses 'oo', which the tool reads as a variable. Infinity is written +oo or -oo.");
var unsupportedNode = expression.Nodes.FirstOrDefault(node => UNSUPPORTED_NODE_TYPES.Contains(node.GetType()));
if (unsupportedNode is not null)
throw new MathComputationException($"Argument '{argumentName}' contains '{unsupportedNode.ToString().Shorten(MAX_SHOWN_LENGTH)}', which the tool does not support.");
return expression;
}
@@ -79,6 +132,10 @@ public static partial class MathExpressionReader
{
throw new MathComputationException($"Argument '{argumentName}' cannot be read: {exception.Message}.");
}
catch (UnrecognizedFunctionParseException exception)
{
throw new MathComputationException(DescribeUnrecognizedFunction(exception.Message, argumentName));
}
catch (ParseException exception)
{
throw new MathComputationException(DescribeParseError(exception.Message, argumentName));
@@ -90,10 +147,11 @@ public static partial class MathExpressionReader
/// </summary>
/// <remarks>
/// AngouriMath downcasts while it parses: it reads 0.1 as 1/10, but 6.62607015e-34 as an inexact
/// decimal and 1e-60 as 0, see AngouriMathBehaviorTests. Simplifying then drops an inexact decimal
/// from a sum, so 1 + 1e-40 would be exactly 1. The reader therefore parses without downcasting,
/// which leaves every number a decimal, and turns each into its fraction or integer. A literal
/// with an exponent beyond MathLimits.MAX_EXACT_DIGITS stays a decimal.
/// decimal and 1e-60 as 0, see AngouriMathBehaviorTests. An inexact decimal leaves every value it
/// takes part in inexact, and up to version 2.6.0, simplifying even dropped it from a sum, so
/// 1 + 1e-40 was exactly 1. The reader therefore parses without downcasting, which leaves every
/// number a decimal, and turns each into its fraction or integer. A literal with an exponent beyond
/// MathLimits.MAX_EXACT_DIGITS stays a decimal.
/// </remarks>
private static Entity WithExactLiterals(Entity expression) => expression.Replace(node => node is Entity.Number.Real literal and not Entity.Number.Rational ? ExactValueOf(literal) : node);
@@ -122,6 +180,14 @@ public static partial class MathExpressionReader
return $"Argument '{argumentName}' has no operator between '{left}' and '{right}' at column {column}. Multiplication is written '*', as in 2*x, and a function takes its argument in parentheses, as in sin(x).";
}
private static string DescribeUnrecognizedFunction(string message, string argumentName)
{
var match = UnrecognizedFunctionName().Match(message);
return match.Success
? $"Argument '{argumentName}' uses the function '{match.Groups["name"].Value}', which the tool does not support."
: $"Argument '{argumentName}' uses a function or an operator which the tool does not support.";
}
private static string DescribeParseError(string message, string argumentName)
{
var match = ParseErrorPosition().Match(message);
@@ -155,10 +221,18 @@ public static partial class MathExpressionReader
return count;
}
// zeta(3), but neither x_zeta(3) nor zeta (3): the parser reads no function in either
[GeneratedRegex(@"(?<![\p{L}\p{N}_])(?<name>\p{L}[\p{L}\p{N}_]*)\(")]
private static partial Regex FunctionNames();
// There should be an operator between [@0,0:0='2',<185>,1:0] and [@1,1:1='x',<189>,1:1], while parsing `2x`
[GeneratedRegex(@"='(?<left>.*?)',<\d+>,\d+:\d+\] and \[@\d+,\d+:\d+='(?<right>.*?)',<\d+>,\d+:(?<column>\d+)\]")]
private static partial Regex MissingOperatorTokens();
// there is no function trunc: AngouriMath has no rounding functions. …, or: isprime is not a function in AngouriMath: …
[GeneratedRegex(@"^(?:there is no function (?<name>[^\s:]+):|(?<name>[^\s:]+) is not a function\b)")]
private static partial Regex UnrecognizedFunctionName();
// line 1:4 extraneous input '*' expecting {'-', '+', ...}, while parsing `2 + * 3`
[GeneratedRegex(@"^line \d+:(?<column>\d+) (?<reason>.*?)(?: expecting .*)?(?:, while parsing `.*`)?$", RegexOptions.Singleline)]
private static partial Regex ParseErrorPosition();
@@ -13,14 +13,17 @@ namespace AIStudio.Tools.Mathematics;
/// </summary>
/// <remarks>
/// AngouriMath computes an exact power or factorial in full, and an expansion term by term, without
/// checking its cancellation token meanwhile: 9^9^9, (10^9)!, and the expansion of (x + y)^500 run
/// on long past any budget, see AngouriMathBehaviorTests. The guards estimate the size of such a
/// checking its cancellation token meanwhile: (10^9)! and the expansion of (x + y)^500 run on long
/// past any budget, and so did 9^9^9 up to version 2.6.0; since version 2.7.0, AngouriMath leaves a
/// power of more than sixteen million bits written instead. The guards estimate the size of such a
/// result from the expression alone, before anything is computed, and refuse it when it would be
/// larger than any result the tools return anyway.<br/><br/>
/// The estimate works from the inside out, so the inner power of 9^9^9^9 is known before the outer
/// one is judged. Only numbers of known value count: a power of a variable is never computed as a
/// number. Call the guards inside a computation of MathComputationService, since they evaluate the
/// exponents and the arguments of factorials, which have passed the guards before.
/// exponents and the arguments of factorials, which have passed the guards before.<br/><br/>
/// The same holds for the special functions polygamma and gamma(a, z), which AngouriMath computes for as
/// long as their arguments ask, see MathLimits. CheckExactSize refuses them beyond their limits as well.
/// </remarks>
public static class MathGuards
{
@@ -28,11 +31,27 @@ public static class MathGuards
/// <summary>
/// Refuses an expression whose exact evaluation would produce a number of more than
/// MathLimits.MAX_EXACT_DIGITS digits.
/// MathLimits.MAX_EXACT_DIGITS digits, or which takes a special function beyond its limits.
/// </summary>
/// <param name="expression">The expression to be evaluated or simplified.</param>
/// <exception cref="MathComputationException">A part of the expression would grow too large.</exception>
public static void CheckExactSize(Entity expression) => EstimateDigits(expression);
/// <exception cref="MathComputationException">A part of the expression would grow too large or take too long.</exception>
public static void CheckExactSize(Entity expression) => EstimateDigits(expression, false);
/// <summary>
/// Refuses an expression whose variables have values, as at the sample points of NumericCheck, when one of its
/// powers or factorials would have more than MathLimits.MAX_EXACT_DIGITS digits, or when it takes a special
/// function beyond its limits.
/// </summary>
/// <remarks>
/// A value of a variable may turn a part which CheckExactSize let through into one which runs on long past
/// the budget: x = 0.61 makes (10^6 * x)! the factorial of 610,000, and x^100000 a fraction of hundreds of
/// thousands of digits; in polygamma(1000 * x, 2), x becomes the order. Unlike CheckExactSize, it takes the
/// largest of the parts of a sum, a product, or a quotient instead of adding up their digits: the checks
/// evaluate long sums, such as the expansion of (x + 1)^200, whose terms each have few digits.
/// </remarks>
/// <param name="expression">The expression with the values of its variables in their place.</param>
/// <exception cref="MathComputationException">A part of the expression would grow too large or take too long.</exception>
public static void CheckValueAtPoint(Entity expression) => EstimateDigits(expression, true);
/// <summary>
/// Refuses an expression whose expansion would take a power of a sum beyond
@@ -62,14 +81,19 @@ public static class MathGuards
/// An upper bound for sums, products, and quotients: the digits of numerator and denominator
/// add up. A number which is not exact, such as a decimal of the current precision, needs none.
/// </remarks>
private static double EstimateDigits(Entity node)
/// <param name="node">The node to be estimated.</param>
/// <param name="largestPart">Whether a sum, a product, or a quotient counts the digits of its largest part only, see CheckValueAtPoint.</param>
private static double EstimateDigits(Entity node, bool largestPart)
{
var digits = node switch
{
Entity.Number.Rational rational => DigitsOf(rational.ERational.Numerator) + DigitsOf(rational.ERational.Denominator),
Entity.Powf power => EstimatePower(power),
Entity.Factorialf factorial => EstimateFactorial(factorial),
_ => node.DirectChildren.Sum(EstimateDigits),
Entity.Powf power => EstimatePower(power, largestPart),
Entity.Factorialf factorial => EstimateFactorial(factorial, largestPart),
Entity.Polygammaf polygamma => EstimatePolygamma(polygamma, largestPart),
Entity.IncompleteGammaf gamma => EstimateIncompleteGamma(gamma, largestPart),
_ when largestPart => node.DirectChildren.Select(child => EstimateDigits(child, true)).DefaultIfEmpty(0).Max(),
_ => node.DirectChildren.Sum(child => EstimateDigits(child, false)),
};
if (digits > MathLimits.MAX_EXACT_DIGITS)
@@ -78,10 +102,10 @@ public static class MathGuards
return digits;
}
private static double EstimatePower(Entity.Powf power)
private static double EstimatePower(Entity.Powf power, bool largestPart)
{
var baseDigits = EstimateDigits(power.Base);
var exponentDigits = EstimateDigits(power.Exponent);
var baseDigits = EstimateDigits(power.Base, largestPart);
var exponentDigits = EstimateDigits(power.Exponent, largestPart);
if (MathVariables.HasAny(power.Base))
return baseDigits + exponentDigits;
@@ -104,9 +128,9 @@ public static class MathGuards
return magnitude * Math.Max(baseDigits, 0);
}
private static double EstimateFactorial(Entity.Factorialf factorial)
private static double EstimateFactorial(Entity.Factorialf factorial, bool largestPart)
{
var argumentDigits = EstimateDigits(factorial.Argument);
var argumentDigits = EstimateDigits(factorial.Argument, largestPart);
var argument = ValueOf(factorial.Argument);
if (argument is null)
return argumentDigits;
@@ -119,6 +143,43 @@ public static class MathGuards
return n * Math.Log10(n / Math.E) + Math.Log10(2 * Math.PI * n) / 2 + 1;
}
private static double EstimatePolygamma(Entity.Polygammaf polygamma, bool largestPart)
{
var digits = EstimateDigits(polygamma.Order, largestPart) + EstimateDigits(polygamma.Argument, largestPart);
var order = ValueOf(polygamma.Order);
if (order > MathLimits.MAX_POLYGAMMA_ORDER)
throw new MathComputationException(string.Create(CultureInfo.InvariantCulture, $"'{Show(polygamma)}' has the order {order.Value:0.###}. The tool cannot stop the computation of polygamma midway, and its time grows with the order, so the order is limited to {MathLimits.MAX_POLYGAMMA_ORDER}."));
return digits;
}
private static double EstimateIncompleteGamma(Entity.IncompleteGammaf gamma, bool largestPart)
{
var digits = EstimateDigits(gamma.Parameter, largestPart) + EstimateDigits(gamma.LowerLimit, largestPart);
var argument = NumberOf(gamma.LowerLimit);
if (argument is not null && AbsoluteValueOf(argument) > MathLimits.MAX_INCOMPLETE_GAMMA_ARGUMENT)
throw new MathComputationException(string.Create(CultureInfo.InvariantCulture, $"'{Show(gamma)}' takes gamma(a, z) at a z of about {AbsoluteValueOf(argument):0.###} 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 {MathLimits.MAX_INCOMPLETE_GAMMA_ARGUMENT:N0}."));
var parameter = NumberOf(gamma.Parameter);
if (parameter is not null && !IsAllowedIncompleteGammaParameter(parameter))
throw new MathComputationException(string.Create(CultureInfo.InvariantCulture, $"'{Show(gamma)}' takes gamma(a, z) for a = {Show(parameter)}. 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 {MathLimits.MIN_INCOMPLETE_GAMMA_PARAMETER} to {MathLimits.MAX_INCOMPLETE_GAMMA_PARAMETER}."));
return digits;
}
private static bool IsAllowedIncompleteGammaParameter(Entity.Number.Complex parameter)
{
var real = parameter.RealPart.EDecimal.ToDouble();
return parameter.ImaginaryPart.EDecimal.IsZero && real is >= MathLimits.MIN_INCOMPLETE_GAMMA_PARAMETER and <= MathLimits.MAX_INCOMPLETE_GAMMA_PARAMETER;
}
/// <summary>
/// The value of a part without variables, as a number, or null when it has none.
/// </summary>
private static Entity.Number.Complex? NumberOf(Entity part) => MathVariables.HasAny(part) ? null : part.Evaled as Entity.Number.Complex;
private static double AbsoluteValueOf(Entity.Number.Complex number) => double.Hypot(number.RealPart.EDecimal.ToDouble(), number.ImaginaryPart.EDecimal.ToDouble());
/// <summary>
/// The value of a part without variables, as a double, or null when it has none.
/// </summary>
@@ -46,4 +46,36 @@ public static class MathLimits
/// The most significant digits a decimal result may have.
/// </summary>
public const int MAX_DIGITS = 100;
/// <summary>
/// The highest order n of polygamma(n, x) which is computed.
/// </summary>
/// <remarks>
/// AngouriMath computes polygamma without checking its cancellation token, and its time grows with the
/// order: on a Mac, with 100 digits, order 100 takes 0.2 seconds at most, order 1,000 up to 1.5 seconds,
/// and order 3,000 over 2 seconds. A derivative of order 10 of digamma is polygamma(10, x).
/// </remarks>
public const int MAX_POLYGAMMA_ORDER = 100;
/// <summary>
/// The largest absolute value of z in the incomplete gamma function gamma(a, z) which is computed.
/// </summary>
/// <remarks>
/// AngouriMath computes gamma(a, z) without checking its cancellation token, and its time grows with z, the
/// more so for a parameter a which is negative or not real. Within the limits of z and a, it takes
/// 0.5 seconds at most on a Mac, with 100 digits, as for gamma(-1/2, 1000), while gamma(-199/2, 100)
/// takes 2 seconds, gamma(-14 + 14*i, 1000) 1.3 seconds, gamma(i, 2000) 3 seconds, and
/// gamma(10000, 10000) longer than the time budget.
/// </remarks>
public const int MAX_INCOMPLETE_GAMMA_ARGUMENT = 1_000;
/// <summary>
/// The smallest parameter a of gamma(a, z) which is computed; a has to be real.
/// </summary>
public const int MIN_INCOMPLETE_GAMMA_PARAMETER = -20;
/// <summary>
/// The largest parameter a of gamma(a, z) which is computed; a has to be real.
/// </summary>
public const int MAX_INCOMPLETE_GAMMA_PARAMETER = 200;
}
@@ -0,0 +1,58 @@
using AngouriMath;
namespace AIStudio.Tools.Mathematics;
/// <summary>
/// Takes a set of solutions apart into its members.
/// </summary>
/// <remarks>
/// AngouriMath answers an equation with a finite set, or with infinitely many solutions as a family: an indexed
/// union such as union({ pi / 6 + 2 * pi * n, pi - pi / 6 + 2 * pi * n }, n in ZZ), which binds its index n. A family
/// may hold another one, and a union may join families and finite sets. Each member of such a set is one solution
/// for every value of its indices, see SolutionMember.
/// </remarks>
public static class MathSolutions
{
/// <summary>
/// Whether a part of the set restates the equation, since AngouriMath found no solution in closed form for it.
/// </summary>
/// <param name="solutions">The set of solutions.</param>
/// <returns>True when a part of the set is a set builder of the equation.</returns>
public static bool HasUnsolvedPart(Entity solutions) => solutions switch
{
Entity.Set.ConditionalSet => true,
Entity.Set.Unionf union => HasUnsolvedPart(union.Left) || HasUnsolvedPart(union.Right),
Entity.Set.IndexedUnionf family => HasUnsolvedPart(family.Body),
_ => false,
};
/// <summary>
/// The members of a set of solutions, in the order AngouriMath gave them.
/// </summary>
/// <param name="solutions">The set of solutions.</param>
/// <returns>The members, or null for a set which is no list of solutions, such as an interval.</returns>
public static IReadOnlyList<SolutionMember>? MembersOf(Entity solutions)
{
var members = new List<SolutionMember>();
return Collect(solutions, [], members) ? members : null;
}
private static bool Collect(Entity part, IReadOnlyList<SolutionIndex> indices, List<SolutionMember> members)
{
switch (part)
{
case Entity.Set.FiniteSet finite:
members.AddRange(finite.Select(value => new SolutionMember(value, indices)));
return true;
case Entity.Set.Unionf union:
return Collect(union.Left, indices, members) && Collect(union.Right, indices, members);
case Entity.Set.IndexedUnionf { Var: Entity.Variable index, Over: Entity.Set over } family:
return Collect(family.Body, [..indices, new SolutionIndex(index, over)], members);
default:
return false;
}
}
}
@@ -17,8 +17,8 @@ namespace AIStudio.Tools.Mathematics;
/// A point where either side has no value, such as a pole, is skipped. Agreement at the points
/// supports the equality; it does not prove it.<br/><br/>
/// A derivative is compared with the central difference of its function, over a step of 1e-20 at 60
/// digits. The integer parameter of periodic solutions, which AngouriMath names n_1, takes the values
/// -1, 0, and 1 instead, since such a solution holds at integers only.<br/><br/>
/// digits. The index of a family of solutions takes three integers of its set instead, -1, 0, and 1 for
/// any integer, since such a solution holds for those values only.<br/><br/>
/// Call it inside a computation of MathComputationService.
/// </remarks>
public static class NumericCheck
@@ -40,8 +40,19 @@ public static class NumericCheck
/// <summary>
/// The precision of a derivative check: the central difference divides by its tiny step.
/// </summary>
/// <remarks>
/// It suffices for a function no larger than its derivative, with 20 digits to spare. The difference
/// of a larger one, such as 100! + sin(x) or gamma(100, x), would be lost in the rounding of its
/// values, so the check takes one digit more for each power of ten by which the function exceeds its
/// derivative, see DerivativePrecisionAt.
/// </remarks>
private const int DERIVATIVE_PRECISION = 60;
/// <summary>
/// The highest precision of a derivative check; a point which would need more is left out.
/// </summary>
private const int MAX_DERIVATIVE_PRECISION = 1_000;
/// <summary>
/// The step of the central difference: rounding at 60 digits costs about 1e-40 of it, and its own
/// error, about the square of the step, 1e-40 as well.
@@ -52,6 +63,16 @@ public static class NumericCheck
private static readonly EDecimal DERIVATIVE_TOLERANCE = EDecimal.FromString("1e-20");
/// <summary>
/// The integers an index of a family of solutions may take, in the order they are tried.
/// </summary>
private static readonly int[] INDEX_CANDIDATES = [-1, 0, 1, 2, -2, 3, -3];
/// <summary>
/// How many integers of its set an index takes across the sample points.
/// </summary>
private const int INDEX_VALUES = 3;
/// <summary>
/// Checks whether two expressions agree at every sample point where both have a value.
/// </summary>
@@ -62,17 +83,30 @@ public static class NumericCheck
/// <param name="left">One expression.</param>
/// <param name="right">The other expression.</param>
/// <returns>What the check found.</returns>
public static NumericCheckOutcome AreEqual(Entity left, Entity right)
public static NumericCheckOutcome AreEqual(Entity left, Entity right) => AreEqual(left, right, []);
/// <summary>
/// Checks whether two expressions agree at every sample point where both have a value, with the indices of a
/// family of solutions taking integers of their sets.
/// </summary>
/// <param name="left">One expression.</param>
/// <param name="right">The other expression.</param>
/// <param name="indices">The indices which occur freely in the expressions, e.g., n for any integer.</param>
/// <returns>What the check found; not possible when an index takes none of the integers tried.</returns>
public static NumericCheckOutcome AreEqual(Entity left, Entity right, IReadOnlyList<SolutionIndex> indices)
{
left = WithoutCondition(left);
right = WithoutCondition(right);
var variables = MathVariables.FreeIn(left).Concat(MathVariables.FreeIn(right)).Distinct().OrderBy(variable => variable.Name, StringComparer.Ordinal).ToArray();
var indexValues = IndexValues(indices);
if (indexValues.Values.Any(values => values.Count == 0))
return NumericCheckOutcome.NOT_POSSIBLE;
using var precision = MathS.Settings.DecimalPrecisionContext.Set(EContext.ForPrecision(PRECISION));
var validPoints = 0;
for (var point = 0; point < SAMPLE_POINTS; point++)
{
var assignment = SampleAssignment(point, variables);
var assignment = SampleAssignment(point, variables, indexValues);
var leftValue = ValueAt(left, assignment);
var rightValue = ValueAt(right, assignment);
if (leftValue is null || rightValue is null)
@@ -106,12 +140,21 @@ public static class NumericCheck
var assignment = SampleAssignment(point, variables);
var at = assignment[variable];
var claimed = ValueAt(derivative, assignment);
var above = ValueAt(function, With(assignment, variable, (at + DERIVATIVE_STEP).InnerSimplified));
var below = ValueAt(function, With(assignment, variable, (at - DERIVATIVE_STEP).InnerSimplified));
if (claimed is null || above is null || below is null)
var value = ValueAt(function, assignment);
if (claimed is null || value is null)
continue;
var difference = NumericEvaluator.EvaluateAt(((Entity)above - below) / TWO_DERIVATIVE_STEPS, DERIVATIVE_PRECISION);
var digits = DerivativePrecisionAt(value, claimed);
if (digits > MAX_DERIVATIVE_PRECISION)
continue;
using var pointPrecision = MathS.Settings.DecimalPrecisionContext.Set(EContext.ForPrecision(digits));
var above = ValueAt(function, With(assignment, variable, (at + DERIVATIVE_STEP).InnerSimplified));
var below = ValueAt(function, With(assignment, variable, (at - DERIVATIVE_STEP).InnerSimplified));
if (above is null || below is null)
continue;
var difference = NumericEvaluator.EvaluateAt(((Entity)above - below) / TWO_DERIVATIVE_STEPS, digits);
validPoints++;
if (!AreClose(claimed, difference, DERIVATIVE_TOLERANCE))
return NumericCheckOutcome.FAILED;
@@ -121,11 +164,32 @@ public static class NumericCheck
}
/// <summary>
/// Whether AngouriMath named a variable as the integer parameter of periodic solutions, as in pi / 6 + 2 * pi * n_1.
/// The precision a central difference needs at a point: DERIVATIVE_PRECISION, and one digit more for each
/// power of ten by which the function exceeds its derivative.
/// </summary>
/// <param name="variable">The variable.</param>
/// <returns>True for n_1, n_2, and so on.</returns>
public static bool IsIntegerParameter(Entity.Variable variable) => variable.Name.StartsWith("n_", StringComparison.Ordinal) && variable.Name.Length > 2 && variable.Name[2..].All(char.IsAsciiDigit);
/// <remarks>
/// Rounding to p digits changes each value of the function by about 10^-p of it, which the division by
/// the step of 1e-20 enlarges to 10^(20 - p) of it. To stay within DERIVATIVE_TOLERANCE of the derivative,
/// p has to exceed 40 plus the decimal logarithm of their ratio; DERIVATIVE_PRECISION keeps 20 digits
/// more. Against a derivative of 0, the tolerance is absolute.
/// </remarks>
private static int DerivativePrecisionAt(Entity.Number.Complex value, Entity.Number.Complex derivative)
{
var ratio = DecimalLogarithmOfSize(value) - (IsZero(derivative) ? 0 : DecimalLogarithmOfSize(derivative));
return DERIVATIVE_PRECISION + (int)Math.Max(0, Math.Ceiling(ratio));
}
/// <summary>
/// The decimal logarithm of the larger part of a number, roughly, also beyond the range of a double.
/// </summary>
private static double DecimalLogarithmOfSize(Entity.Number.Complex number)
{
var size = EDecimal.Max(number.RealPart.EDecimal.Abs(), number.ImaginaryPart.EDecimal.Abs());
if (size.IsZero)
return double.NegativeInfinity;
return size.Exponent.ToInt64Checked() + size.Mantissa.Abs().GetDigitCountAsInt64() - 1;
}
/// <summary>
/// The values of the variables at one sample point.
@@ -133,15 +197,40 @@ public static class NumericCheck
/// <param name="point">The number of the point, from zero.</param>
/// <param name="variables">The variables, in a fixed order.</param>
/// <returns>Each variable with its exact value.</returns>
public static IReadOnlyDictionary<Entity.Variable, Entity> SampleAssignment(int point, IReadOnlyList<Entity.Variable> variables)
public static IReadOnlyDictionary<Entity.Variable, Entity> SampleAssignment(int point, IReadOnlyList<Entity.Variable> variables) => SampleAssignment(point, variables, new Dictionary<Entity.Variable, IReadOnlyList<Entity>>());
/// <summary>
/// The values of the variables at one sample point, where the indices of a family of solutions take integers of their sets.
/// </summary>
/// <param name="point">The number of the point, from zero.</param>
/// <param name="variables">The variables, in a fixed order.</param>
/// <param name="indices">The indices among the variables.</param>
/// <returns>Each variable with its exact value; an index which takes none of the integers tried is left out.</returns>
public static IReadOnlyDictionary<Entity.Variable, Entity> SampleAssignment(int point, IReadOnlyList<Entity.Variable> variables, IReadOnlyList<SolutionIndex> indices) => SampleAssignment(point, variables, IndexValues(indices));
/// <summary>
/// The integers each index takes, at most INDEX_VALUES of them.
/// </summary>
private static Dictionary<Entity.Variable, IReadOnlyList<Entity>> IndexValues(IReadOnlyList<SolutionIndex> indices)
{
var values = new Dictionary<Entity.Variable, IReadOnlyList<Entity>>(indices.Count);
foreach (var index in indices)
values[index.Variable] = [..INDEX_CANDIDATES.Where(index.Takes).Take(INDEX_VALUES).Select(Entity (candidate) => Entity.Number.Integer.Create(candidate))];
return values;
}
private static Dictionary<Entity.Variable, Entity> SampleAssignment(int point, IReadOnlyList<Entity.Variable> variables, IReadOnlyDictionary<Entity.Variable, IReadOnlyList<Entity>> indexValues)
{
var assignment = new Dictionary<Entity.Variable, Entity>(variables.Count);
for (var index = 0; index < variables.Count; index++)
{
// An integer parameter takes -1, 0, and 1, since a periodic solution holds only at integers:
if (IsIntegerParameter(variables[index]))
// An index takes integers of its set, since a family of solutions holds only there:
if (indexValues.TryGetValue(variables[index], out var values))
{
assignment[variables[index]] = Entity.Number.Integer.Create((point + index) % 3 - 1);
if (values.Count > 0)
assignment[variables[index]] = values[(point + index) % values.Count];
continue;
}
@@ -159,7 +248,7 @@ public static class NumericCheck
/// </summary>
/// <param name="expression">The expression.</param>
/// <param name="assignment">The value of each variable.</param>
/// <returns>The value, or null for no value, an infinite one, or one AngouriMath cannot evaluate.</returns>
/// <returns>The value, or null for no value, an infinite one, one MathGuards.CheckValueAtPoint refuses, or one AngouriMath cannot evaluate.</returns>
public static Entity.Number.Complex? ValueAt(Entity expression, IReadOnlyDictionary<Entity.Variable, Entity> assignment)
{
try
@@ -168,13 +257,18 @@ public static class NumericCheck
foreach (var (variable, value) in assignment)
substituted = substituted.Substitute(variable, value);
// A value of a variable may make a factorial or a power too large to be computed exactly, as x = 2.23 in
// (10^6 * x)!, or take a special function beyond its limits, as in gamma(1/2, 1000 * x). The check comes
// first, since EvaluableNumerical already computes the exact value:
MathGuards.CheckValueAtPoint(substituted);
if (!substituted.EvaluableNumerical)
return null;
//
// A polynomial at a sample point stays exact. Anything else is evaluated without the downcasting which turns
// tiny values into 0, and so is an exact 0: simplifying takes a tiny value such as 6.62607015e-34 * sin(0.61)
// for 0 at this precision, see AngouriMathBehaviorTests:
// tiny values into 0, and so is an exact 0: simplifying takes a value below about 1e-1000 for 0, and up to
// version 2.6.0, it took a tiny value such as 6.62607015e-34 * sin(0.61) for 0 at this precision, see
// AngouriMathBehaviorTests:
//
var exact = NumericEvaluator.ExactValueOf(substituted);
var number = exact is not null && !IsZero(exact) ? exact : NumericEvaluator.EvaluateAt(substituted, MathS.Settings.DecimalPrecisionContext.Value.Precision.ToInt32Checked());
@@ -82,9 +82,10 @@ public static class NumericEvaluator
}
//
// Where AngouriMath rounds to decimal places, a value far below 1 keeps only some of its digits, and a
// tiny one none at all. The precision therefore grows by the leading zeros of the value, and a value of
// zero is evaluated again with twice the digits, until MAX_PRECISION. More digits cannot change an
// Up to version 2.6.0, AngouriMath rounded to decimal places, so a value far below 1 kept only some of its
// digits, and a tiny one none at all. The precision therefore grows by the leading zeros of the value, and a
// value of zero is evaluated again with twice the digits, until MAX_PRECISION. Since version 2.7.0, a value
// keeps its digits, and this only costs time; it stays as a safeguard. More digits cannot change an
// integral's value of zero, which comes from the quadrature:
//
var shift = 0;
@@ -175,7 +176,8 @@ public static class NumericEvaluator
}
catch (Exception exception) when (exception is not OperationCanceledException)
{
throw new MathComputationException($"The integrand of '{Show(integral)}' cannot be evaluated numerically: {exception.Message.Shorten(MAX_SHOWN_LENGTH)}");
// The message of AngouriMath addresses a developer, asking to call .Evaled or Simplify() first:
throw new MathComputationException($"The integrand of '{Show(integral)}' cannot be evaluated point by point, which a numerical integration needs, e.g., since it holds gamma(a, z), a derivative, or a limit.");
}
var result = DoubleExponentialQuadrature.Integrate(integrand, lower, upper, token);
@@ -229,10 +231,11 @@ public static class NumericEvaluator
/// </summary>
/// <remarks>
/// By default, AngouriMath downcasts: it turns a number which looks like an integer at the precision into that
/// integer, and so a tiny value such as 1.380649e-23 * 300 into 0, see AngouriMathBehaviorTests. This evaluation
/// does without. Then AngouriMath rounds the quotient of two integers to as many decimal places as the precision
/// has digits, so 21/10^50 vanishes at 30 digits. The precision therefore grows by the leading zeros of the
/// smallest fraction in the expression, up to MAX_PRECISION.
/// integer, and so, at 30 digits, 1.380649e-23 * 300 into 0, see AngouriMathBehaviorTests. This evaluation
/// does without. Up to version 2.6.0, AngouriMath then rounded the quotient of two integers to as many decimal
/// places as the precision has digits, so 21/10^50 vanished at 30 digits. The precision therefore grows by the
/// leading zeros of the smallest fraction in the expression, up to MAX_PRECISION. Since version 2.7.0, the
/// quotient keeps its digits; the growth stays as a safeguard.
/// </remarks>
/// <param name="expression">The expression, without variables.</param>
/// <param name="precision">How many significant digits to compute with, at least.</param>
@@ -252,8 +255,8 @@ public static class NumericEvaluator
/// AngouriMath simplifies a value below about 1e-1000 to 0, e.g., pi/10^1500, see AngouriMathBehaviorTests.
/// A fraction that small, such as 1e-2000, leaves the 0 in doubt. Otherwise, a true 0, as for sin(pi),
/// evaluates to rounding noise which changes with the precision, but a tiny value, as for exp(-3000), keeps
/// its digits. A quotient such as pi/10^1500 evaluates to 0 as well, since AngouriMath rounds it to decimal
/// places; its 0 stands.
/// its digits. Up to version 2.6.0, a quotient such as pi/10^1500 evaluated to 0 as well, since AngouriMath
/// rounded it to decimal places; such a 0 stands.
/// </remarks>
private static bool MayBeTiny(Entity expression, int digits)
{
@@ -0,0 +1,18 @@
using AngouriMath;
namespace AIStudio.Tools.Mathematics;
/// <summary>
/// The index of a family of solutions, such as n in union({ pi / 6 + 2 * pi * n }, n in ZZ), with the set it ranges over.
/// </summary>
/// <param name="Variable">The index, which the family binds.</param>
/// <param name="Over">The set the index ranges over, e.g., the integers.</param>
public sealed record SolutionIndex(Entity.Variable Variable, Entity.Set Over)
{
/// <summary>
/// Whether the index may take an integer, as far as AngouriMath can decide it.
/// </summary>
/// <param name="value">The integer.</param>
/// <returns>True when the set of the index surely contains the integer.</returns>
public bool Takes(int value) => this.Over.TryContains(Entity.Number.Integer.Create(value), out var contains) && contains;
}
@@ -0,0 +1,10 @@
using AngouriMath;
namespace AIStudio.Tools.Mathematics;
/// <summary>
/// One member of a set of solutions: a single solution, or a solution for every value of its indices.
/// </summary>
/// <param name="Value">The solution, in which the indices occur freely.</param>
/// <param name="Indices">The indices of the families which hold the solution, from the outermost one; empty for a single solution.</param>
public sealed record SolutionMember(Entity Value, IReadOnlyList<SolutionIndex> Indices);
@@ -94,7 +94,7 @@ public sealed class ComputeSymbolicallyTool(SettingsManager settingsManager, Mat
- `result` is the answer in plain syntax, and `result_latex` the same for your reply. A `condition` says where the result holds, e.g., `not x - 1 = 0`; mention it.
- When `complete` is false, the tool found no closed form, and `result` still holds the integral, the limit, or the equation. Never present it as an answer; `calculate` gives a definite integral numerically.
- `verification` says whether the result was checked numerically: `passed`, `failed`, or `not_possible`. Never present a result with `failed` as correct, and say when the check was `not_possible`.
- Solutions may be complex; `real` tells for each one with a value. n_1 stands for any integer, r_1 for any real number, and C for any constant.
- Solutions may be complex; `real` tells for each one with a value. A solution with `holds_for` is one solution for every value of its index, such as n in pi / 6 + 2 * pi * n; `at_index_0` gives it for the index 0, with its decimal. `issues` say what other names in a result stand for, such as r_1 or C.
""",
Function = new()
{
@@ -390,13 +390,31 @@ public sealed class ComputeSymbolicallyTool(SettingsManager settingsManager, Mat
issues.Add("The expression has no '=', so it was solved for expression = 0.");
}
var solutions = statement.Solve(variable);
json["variable"] = variable.Name;
Solutions(json, issues, expression, statement, variable, statement.Solve(variable));
}
/// <summary>
/// Writes the solutions of a statement, and checks each one by inserting it.
/// </summary>
/// <remarks>
/// A family of solutions, such as union({ pi / 6 + 2 * pi * n }, n in ZZ), holds one solution for every value of
/// its index, see MathSolutions. Each of its members says so in holds_for, and gives the solution for the index 0
/// with its decimal, since that is the one a model asks for most, as in the time a sum takes to double.
/// </remarks>
/// <param name="json">The result for the model.</param>
/// <param name="issues">The issues of the result.</param>
/// <param name="expression">The expression as the model wrote it.</param>
/// <param name="statement">The statement which was solved.</param>
/// <param name="variable">The variable it was solved for.</param>
/// <param name="solutions">The set of solutions.</param>
internal static void Solutions(JsonObject json, List<string> issues, Entity expression, Entity statement, Entity.Variable variable, Entity solutions)
{
json["result"] = MathFormatting.ToText(solutions, "The set of solutions");
json["result_latex"] = MathFormatting.ToLatex(solutions, "The LaTeX of the solutions");
ExplainParameters(issues, expression, solutions);
if (solutions is Entity.Set.ConditionalSet)
if (MathSolutions.HasUnsolvedPart(solutions))
{
json["complete"] = false;
json["verification"] = Verification(NumericCheckOutcome.NOT_POSSIBLE);
@@ -405,27 +423,50 @@ public sealed class ComputeSymbolicallyTool(SettingsManager settingsManager, Mat
}
json["complete"] = true;
if (solutions is not Entity.Set.FiniteSet finite)
var members = MathSolutions.MembersOf(solutions);
if (members is null)
{
json["verification"] = Verification(NumericCheckOutcome.NOT_POSSIBLE);
return;
}
var outcome = finite.Count == 0 || statement is not Entity.Equalsf ? NumericCheckOutcome.NOT_POSSIBLE : NumericCheckOutcome.PASSED;
var outcome = members.Count == 0 || statement is not Entity.Equalsf ? NumericCheckOutcome.NOT_POSSIBLE : NumericCheckOutcome.PASSED;
var list = new JsonArray();
foreach (var solution in finite)
foreach (var member in members)
{
list.Add(Solution(solution));
list.Add(Solution(member));
if (statement is Entity.Equalsf equation)
outcome = Combined(outcome, NumericCheck.AreEqual(equation.Left.Substitute(variable, solution), equation.Right.Substitute(variable, solution)));
outcome = Combined(outcome, NumericCheck.AreEqual(equation.Left.Substitute(variable, member.Value), equation.Right.Substitute(variable, member.Value), member.Indices));
}
json["solutions"] = list;
json["verification"] = Verification(outcome);
if (finite.Count == 0)
if (members.Count == 0)
issues.Add("There is no solution.");
}
/// <summary>
/// Writes a member of the solutions, and for a member of a family the values its indices take and its solution for the index 0.
/// </summary>
private static JsonObject Solution(SolutionMember member)
{
var json = Solution(member.Value);
if (member.Indices.Count == 0)
return json;
json["holds_for"] = string.Join(" and ", member.Indices.Select(DescribeIndex));
if (!member.Indices.All(index => index.Takes(0)))
return json;
var atIndexZero = member.Indices.Aggregate(member.Value, (solution, index) => solution.Substitute(index.Variable, 0));
json["at_index_0"] = Solution(atIndexZero.Simplify());
return json;
}
private static string DescribeIndex(SolutionIndex index) => index.Over is Entity.Set.SpecialSet.Integers
? $"every integer {index.Variable.Name}"
: $"every {index.Variable.Name} in {MathFormatting.ToText(index.Over, "The set of an index")}";
private static JsonObject Solution(Entity solution)
{
var json = new JsonObject
@@ -479,9 +520,7 @@ public sealed class ComputeSymbolicallyTool(SettingsManager settingsManager, Mat
var original = MathVariables.FreeIn(expression).Select(variable => variable.Name).ToHashSet(StringComparer.Ordinal);
foreach (var variable in MathVariables.FreeIn(result).Where(variable => !original.Contains(variable.Name)))
{
if (NumericCheck.IsIntegerParameter(variable))
issues.Add($"{variable.Name} stands for any integer.");
else if (variable.Name.StartsWith("r_", StringComparison.Ordinal))
if (variable.Name.StartsWith("r_", StringComparison.Ordinal))
issues.Add($"{variable.Name} stands for any real number.");
else if (variable.Name == "C" || variable.Name.StartsWith("C_", StringComparison.Ordinal))
issues.Add($"{variable.Name} stands for any constant.");
+3 -3
View File
@@ -4,9 +4,9 @@
"net10.0": {
"AngouriMath": {
"type": "Direct",
"requested": "[2.6.0, )",
"resolved": "2.6.0",
"contentHash": "2PCeqX7NAOHQcTprqVJJoPjzO137mdEDxdy3/o1dJd8sn3CGjJkEH5rxbKRXmLo8bnsTpLymi8qKC9h5aU/7wA==",
"requested": "[2.8.0, )",
"resolved": "2.8.0",
"contentHash": "N3QM2I3qtwCAULfKQsQhUCU1OHD9sf637QHEYsAMkBdkbCPl/2Xc5yeo7FLW2e9Q4XIHnW3spQ4uYTadujQGiQ==",
"dependencies": {
"Antlr4.Runtime.Standard": "4.13.1",
"GenericTensor": "1.0.4",
@@ -34,6 +34,7 @@
- Improved the ERI data sources which organizations provide through configuration plugins: AI Studio removes spaces and line breaks around their tokens and passwords and leaves out a data source whose username, token, or password contains a character which the ERI server cannot receive, noting this in the log.
- Improved the messages about failed requests to ERI servers, which no longer repeat the values sent along with a request.
- Improved the Flatpak version of AI Studio for Linux: it now runs on the GNOME 51 runtime, ships the same up-to-date version of .NET, and is built with the same up-to-date version of Rust as all other versions of AI Studio.
- Improved the Mathematics prototype: it takes more limits correctly, answers more equations within its time limit, and finds all solutions of equations with infinitely many, such as sin(x) = 1/2. The AI still gets a single value as well, such as the years in which a sum doubles.
- Changed the icons of AI Studio to Lucide, an open-source icon set. All icons now share one style, and each feature shows the same icon wherever you meet it.
- Fixed assistant plugins, which all appeared under "Installed Assistants" on the assistants page. Each one now appears under its own category, such as "Business", next to the built-in assistants of that category.
- Fixed the Assistant Builder, which ignored the category you chose for your assistant. You can now also name a category of your own.
@@ -48,6 +49,8 @@
- Fixed the AI-based data validation of classic RAG, which kept passages that the AI had judged as not fitting your question. Now the AI only gets the passages that fit. When the check fails for a passage, AI Studio keeps it, and when it fails for all of them, AI Studio tells you.
- Fixed signing in to a mailbox when your username or password contains characters beyond ASCII, such as umlauts, accents, or Asian characters. Depending on its configuration, a mail server may expect them in another encoding than UTF-8. You can now choose the encoding in the server details of the mailbox, and after a failed sign-in, AI Studio offers to test the connection once more with the encoding common in your region.
- Fixed the tiles on the assistants page, which were narrower when their texts were short, so that the tiles did not line up in columns. All tiles now have the same width, and their start buttons sit at the same height.
- Fixed the Mathematics prototype, which told the AI that a correct derivative or integral had failed its check when the values of the function were far larger than those of its derivative.
- Fixed the Mathematics prototype getting stuck for a long time when it checked a result with a very large factorial or power. Meanwhile, no other calculation could run.
- Upgraded several libraries to improve security.
- Upgraded Tauri to v2.12.7.
- Upgraded PDFium to v158.0.8125.0 and Qdrant Edge to v0.9.0.
@@ -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();
}
+25
View File
@@ -84,6 +84,21 @@ public static class MathematicsChecks
["right/expression"] = "pi ^ 4 / 15",
});
//
// The special functions which solving, integrating, and differentiating return, evaluated and compiled:
//
Expect(failures, "calculate lambertw(0, 2) + polygamma(1, 1) + gamma(2, 1)", Calculation("lambertw(0, 2) + polygamma(1, 1) + gamma(2, 1)", 20), new()
{
["decimal"] = "3.233298451204836571",
["digits"] = "20",
});
Expect(failures, "check the integral of lambertw(0, x) + polygamma(1, x) from 1 to 2", Calculation("integral(lambertw(0, x) + polygamma(1, x), x, 1, 2) = 2*(lambertw(2) - 1 + 1/lambertw(2)) - (lambertw(1) - 1 + 1/lambertw(1)) + 1", 20), new()
{
["numerically_equal"] = "true",
["left/approximate"] = "true",
});
//
// The symbolic operations, each with its numerical check:
//
@@ -136,6 +151,16 @@ public static class MathematicsChecks
["verification"] = "passed",
});
//
// A family of solutions, which takes the membership of its index set:
//
Expect(failures, "solve 2^x = 5", Symbolic(SymbolicOperation.SOLVE, "2^x = 5"), new()
{
["solutions/0/holds_for"] = "every integer n",
["solutions/0/at_index_0/decimal"] = "2.32192809488736",
["verification"] = "passed",
});
return failures;
}
+12 -8
View File
@@ -271,17 +271,19 @@ Logs name a mailbox and its ID, never a subject, a sender or recipient, a folder
Both tools read plain syntax, not LaTeX, which `CalculateTool.SYNTAX` describes for both schemas. The chat renders LaTeX, so each result carries a LaTeX version besides. `MathExpressionReader` parses with `ExplicitParsingOnly`: otherwise AngouriMath reads `x2` as `x^2` and `foo(3)` as `foo * 3`, and the model would get an answer to a question it did not ask. Before parsing, the reader refuses what AngouriMath reads differently from what a model means: `!=`, which AngouriMath reads as `a! = b`, while not-equal is `<>`; `|`, which means "divides"; the variable `oo`, while infinity is `+oo` or `-oo`; and more than one `=`. It shortens the parser's messages, which list over 1,000 characters of tokens, to the column and the cause.
Every decimal literal is the fraction it writes, so `0.1 + 0.2` is exactly `3/10` and `6.62607015e-34` is exactly `132521403/200000000000000000000000000000000000000000`. AngouriMath alone does that for some literals only: it downcasts while parsing, keeps `6.62607015e-34` an inexact decimal, and reads `1e-60` as `0`. Simplifying then drops an inexact decimal from a sum, so `1 + 1e-40` would be exactly `1`. The reader therefore parses without downcasting and without AngouriMath's cache of parsed expressions, and turns each literal into its fraction itself.
AngouriMath 2.7.0 and 2.8.0 added about sixty functions, such as `zeta`, `det`, `primepi`, and `re`. The tools support three of them, since solving, integrating, and differentiating return them: `lambertw` (also `productlog`), `polygamma` (also `digamma`), and the incomplete gamma function `gamma(a, z)`. The reader refuses the others by name before parsing, `MathExpressionReader.UNSUPPORTED_FUNCTIONS`, because AngouriMath computes some of them while it parses, such as `det`, `dot`, or `jacobian` of a matrix written out, so nothing of them would be left to refuse afterward. After parsing, it refuses the new kinds of nodes, `MathExpressionReader.UNSUPPORTED_NODE_TYPES`, which also covers the three which come without a name: the double factorial `n!!`, the entry `A[1, 2]` of a matrix, and the product over a set, `product(f, x in S)`.
Every decimal literal is the fraction it writes, so `0.1 + 0.2` is exactly `3/10` and `6.62607015e-34` is exactly `132521403/200000000000000000000000000000000000000000`. AngouriMath alone does that for some literals only: it downcasts while parsing, keeps `6.62607015e-34` an inexact decimal, and reads `1e-60` as `0`. An inexact decimal leaves every value it takes part in inexact, and up to AngouriMath 2.6.0, simplifying even dropped it from a sum, so `1 + 1e-40` was exactly `1`. The reader therefore parses without downcasting and without AngouriMath's cache of parsed expressions, and turns each literal into its fraction itself.
AngouriMath computes `sum(f, k, a, b)` only in closed form, as for powers of `k`, so `sum(k, k, 1, 10^7)` takes no time, while `sum(1/k, k, 1, 1000)` has no value. Such a sum, an infinite one, or a matrix is refused by `NumericEvaluator` in its own words, since AngouriMath's message addresses a developer.
No text the model reads names AngouriMath: neither the instructions and schemas of the tools, nor a refusal or an issue. Where a sentence needs someone who computes, it says "the tool", as in "The tool found no closed form for this integral.": a model would take the name of the library for something it may call or look up. The tests of both tools check their definitions for it.
No text the model reads names AngouriMath: neither the instructions and schemas of the tools, nor a refusal or an issue. Where a sentence needs someone who computes, it says "the tool", as in "The tool found no closed form for this integral.": a model would take the name of the library for something it may call or look up. The tests of both tools check their definitions for it. AngouriMath's own messages name it in three places the tools reach: where it refuses a function by name, as `trunc`, `MathExpressionReader` states only the name; where an integrand has no form to evaluate point by point, as with `gamma(a, z)`, `NumericEvaluator` words the refusal itself instead of asking to call `.Evaled`; and an `AngouriBugException`, which asks to report it to the library, becomes a message of `MathComputationService`. `MathExpressionReaderTests` tries every function of the parser for it.
### Honest Digits
A decimal shows only the digits the computation vouches for. `NumericEvaluator` evaluates twice, with 10 and with 20 guard digits, and keeps the digits in which both agree, because composite expressions lose a digit or two at the end. When fewer digits remain than were asked for, `issues` says so.
Tiny values need care, as with the Planck constant. By default, AngouriMath downcasts while evaluating, too, and takes a value such as `1.380649e-23 * 300` for the integer `0`. `NumericEvaluator.EvaluateAt` evaluates without downcasting. Then AngouriMath rounds a quotient to as many decimal places as the precision has digits, so the precision grows by the leading zeros of the smallest fraction and of the value, up to 1,000 digits. Simplifying, too, takes a tiny value for `0`: below about `1e-1000`, or near the precision where it evaluates a function. An exact `0` is therefore checked numerically. Rounding noise, as for `sin(pi)`, changes with the precision; a tiny value keeps its digits and is reported as a decimal instead. A `0` that remains after 1,000 digits without being exact comes with a note in `issues` that it may stand for a tiny value.
Tiny values need care, as with the Planck constant. By default, AngouriMath downcasts and, at 30 digits, takes a value such as `1.380649e-23 * 300` for the integer `0`. `NumericEvaluator.EvaluateAt` evaluates without downcasting. Up to AngouriMath 2.6.0, a quotient was then rounded to as many decimal places as the precision has digits, so the precision grows by the leading zeros of the smallest fraction and of the value, up to 1,000 digits. Since 2.7.0, a computed value keeps its digits, and the growth stays as a safeguard. Simplifying takes a value below about `1e-1000` for `0`, and up to 2.6.0 also a tiny value near the precision where it evaluates a function. An exact `0` is therefore checked numerically. Rounding noise, as for `sin(pi)`, changes with the precision; a tiny value keeps its digits and is reported as a decimal instead. A `0` that remains after 1,000 digits without being exact comes with a note in `issues` that it may stand for a tiny value.
A definite integral always goes to `DoubleExponentialQuadrature`, never through an antiderivative, which gives wrong values when it jumps between the bounds, and never through `Evaled`, which turns constants into decimals even inside an integral it cannot solve. The quadrature works with doubles and estimates its error. The result is then `approximate`, with its `estimated_error`, and its digits drop to what the error allows, mostly 12 to 15. An integral which does not settle, or which has no finite value at a point, is refused rather than answered with a wrong number.
@@ -290,19 +292,21 @@ A definite integral always goes to `DoubleExponentialQuadrature`, never through
A symbolic answer is only as good as the library which gave it, and AngouriMath changes answers between releases. `compute_symbolically` therefore checks each result numerically where it can, and reports `passed`, `failed`, or `not_possible` in `verification`:
- `simplify`, `expand`, and `factor`: the expression and the result are equal.
- `differentiate`: each order agrees with a central difference of the order before, at 60 digits.
- `differentiate`: each order agrees with a central difference of the order before, at 60 digits, and at one digit more for each power of ten by which the function exceeds its derivative, as for `100! + sin(x)`; the check of an antiderivative works the same way.
- `integrate` without bounds: the derivative of the antiderivative is the integrand.
- `integrate` with bounds: the value agrees with the quadrature.
- `solve`: each solution satisfies the equation.
- `limit`: not checked.
`NumericCheck` compares at six fixed sample points. They are exact rationals, so a polynomial is evaluated exactly, however much the terms of its expansion cancel; everything else is evaluated at 50 digits, without downcasting. Two values agree within a relative tolerance, so tiny values, such as those of a formula with physical constants, are still told apart. Against `0`, the tolerance is absolute, because terms which cancel leave their rounding noise. The points are fixed, so the same call always gets the same verdict. Parameters which AngouriMath brings into a solution, such as `n_1` for any integer, take integer values there. Where AngouriMath finds no closed form, `complete` is false, and `result` still holds the integral, the limit, or the equation.
`NumericCheck` compares at six fixed sample points. They are exact rationals, so a polynomial is evaluated exactly, however much the terms of its expansion cancel; everything else is evaluated at 50 digits, without downcasting. Two values agree within a relative tolerance, so tiny values, such as those of a formula with physical constants, are still told apart. Against `0`, the tolerance is absolute, because terms which cancel leave their rounding noise. The points are fixed, so the same call always gets the same verdict. Where AngouriMath finds no closed form, `complete` is false, and `result` still holds the integral, the limit, or the equation.
An equation with infinitely many solutions, such as `sin(x) = 1/2`, may come back as a family: an indexed union such as `union({ pi / 6 + 2 * pi * n, pi - pi / 6 + 2 * pi * n }, n in ZZ)`, which binds its index `n`. `MathSolutions` takes such a set apart into its members, also when a family holds another one or a union joins families and finite sets. Each member of a family lists the values of its indices in `holds_for`, and, when every index may be 0, gives its solution for the index 0 in `at_index_0`, with its decimal: that is the one a model needs most often, such as the time in which a sum doubles. In the check, an index takes three integers of its set, such as -1, 0, and 1 for any integer, or -1, 1, and 2 for `ZZ \ { 0 }`.
### Limits
AngouriMath does not stop every computation when asked to: `9^9^9`, `(10^9)!`, and the expansion of `(x+y)^500` run on whatever the cancellation token says. `MathGuards` therefore refuses before computing what would take too long. That is a power or a factorial whose exact value would have more than 20,000 digits, estimated from the inside out, and a power of a sum with an exponent above 200, wherever AngouriMath may expand it. An expression has at most 2,000 characters, and a result at most 20,000.
AngouriMath does not stop every computation when asked to: `(10^9)!` and the expansion of `(x+y)^500` run on whatever the cancellation token says, and so did `9^9^9` up to AngouriMath 2.6.0; since 2.7.0, a power of more than sixteen million bits is left written. `MathGuards` therefore refuses before computing what would take too long. That is a power or a factorial whose exact value would have more than 20,000 digits, estimated from the inside out, and a power of a sum with an exponent above 200, wherever AngouriMath may expand it. The same holds for the special functions which solving, integrating, and differentiating return: `MathGuards` refuses `polygamma` above the order 100, and `gamma(a, z)` for an absolute value of `z` above 1,000 or for an `a` outside the real numbers from -20 to 200, see `MathLimits` for the times measured. `NumericCheck` applies these limits at its sample points as well, through `MathGuards.CheckValueAtPoint`, because a value of a variable may make a factorial or a power too large there, as in `(10^6*x)!` or `x^100000`, or become the argument of a special function beyond its limits, as in `gamma(1/2, 10000*x)`; a point which would exceed them is left out. There, a sum counts the digits of its largest term only, so the long sums of an expansion still get checked. `lambertw` needs no limit. An expression has at most 2,000 characters, and a result at most 20,000.
`MathComputationService` runs every computation on a thread of its own with a stack of 64 MB. About 500 nested parentheses overflow the stack of a thread pool thread, and that ends the process. There, it switches off Newton's method for `solve`, whose inexact doubles would pass for exact solutions. It hands the cancellation to AngouriMath. The service has one slot, and a computation gets 10 seconds. The slot becomes free when the computation ends, not when the call gives up: a computation which does not stop holds up the next ones rather than taking more cores.
`MathComputationService` runs every computation on a thread of its own with a stack of 64 MB. About 500 nested parentheses overflow the stack of a thread pool thread, and that ends the process. There, it switches off Newton's method for `solve`, whose inexact roots would pass for exact solutions. Since AngouriMath 2.7.0, this also switches off the Durand–Kerner iteration for polynomials, which never checks the cancellation token. It hands the cancellation to AngouriMath. The service has one slot, and a computation gets 10 seconds. The slot becomes free when the computation ends, not when the call gives up: a computation which does not stop holds up the next ones rather than taking more cores.
### Why There Is No Prompt Injection Filter
@@ -310,7 +314,7 @@ The tools open no path for content from outside AI Studio. A result holds the ex
### AngouriMath
`AngouriMathBehaviorTests` pins the behavior of AngouriMath which the tools build on, such as the traps of the parser, the digits of its functions, and the computations which ignore cancellation. The version is pinned exactly by `packages.lock.json`. Before raising it, read the release notes for silent breaking changes, and run these tests.
`AngouriMathBehaviorTests` pins the behavior of AngouriMath which the tools build on, such as the traps of the parser, the digits of its functions, and the computations which ignore cancellation. The version is pinned exactly by `packages.lock.json`. Before raising it, read the release notes for silent breaking changes, and run these tests. Two of them list every function and operator of the parser and every kind of node: a new one fails them until it is decided on, either refused by `MathExpressionReader` or supported, with a guard in `MathGuards` where AngouriMath computes it without checking the cancellation token.
AngouriMath is marked as trimmable, so a published build of AI Studio contains only the parts of it which the trimmer saw being used, and `Trimming.props` suppresses the warnings about the others. The trim smoke test of `dotnet run -- verify` therefore lets both tools compute a few expressions in a trimmed build, see `MathematicsChecks` in `app/TrimSmokeTest`. When a tool starts to use another part of AngouriMath, such as a new operation, add a check there.