mirror of
https://github.com/MindWorkAI/AI-Studio.git
synced 2026-11-25 23:33:48 +00:00
Upgraded AngouriMath to v2.8.0 (#1235)
This commit is contained in:
1 parent
fae3ceb840
commit
506c06fbfc
24 files changed
+974
-105
No files matched your search
@@ -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);
|
||||
+51
-12
@@ -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.");
|
||||
|
||||
Reference in new issue
Block a user