using AngouriMath;
using PeterO.Numbers;
namespace AIStudio.Tools.Mathematics;
///
/// Checks numerically whether two expressions are equal, at fixed sample points.
///
///
/// A symbolic answer is only as good as the library which gave it, and AngouriMath changes answers
/// between releases. The tools therefore check what they can: a simplification against its input, an
/// antiderivative by its derivative, a solution by inserting it.
/// The sample points are exact rationals between 0.6 and 2.3, so a polynomial is evaluated exactly,
/// however much its terms cancel, and everything else at 50 digits. They are fixed, so the same
/// question gets the same answer every time; the providers cache a conversation from its beginning.
/// 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.
/// A derivative is compared with the central difference of its function, over a step of 1e-20 at 60
/// 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.
/// Call it inside a computation of MathComputationService.
///
public static class NumericCheck
{
private const int SAMPLE_POINTS = 6;
private const int MIN_VALID_POINTS = 3;
private const int PRECISION = 50;
///
/// The values the variables take, in hundredths: irregular, so that no point lies on a pattern
/// such as a multiple of pi, and eleven of them, a prime, so that the variables of a point differ.
///
private static readonly int[] SAMPLE_HUNDREDTHS = [61, 73, 89, 107, 119, 131, 147, 163, 179, 197, 223];
private static readonly EDecimal TOLERANCE = EDecimal.FromString("1e-30");
///
/// The precision of a derivative check: the central difference divides by its tiny step.
///
///
/// 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.
///
private const int DERIVATIVE_PRECISION = 60;
///
/// The highest precision of a derivative check; a point which would need more is left out.
///
private const int MAX_DERIVATIVE_PRECISION = 1_000;
///
/// 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.
///
private static readonly Entity.Number.Rational DERIVATIVE_STEP = Entity.Number.Rational.Create(EInteger.One, EInteger.FromInt32(10).Pow(20));
private static readonly Entity.Number.Rational TWO_DERIVATIVE_STEPS = Entity.Number.Rational.Create(EInteger.FromInt32(2), EInteger.FromInt32(10).Pow(20));
private static readonly EDecimal DERIVATIVE_TOLERANCE = EDecimal.FromString("1e-20");
///
/// The integers an index of a family of solutions may take, in the order they are tried.
///
private static readonly int[] INDEX_CANDIDATES = [-1, 0, 1, 2, -2, 3, -3];
///
/// How many integers of its set an index takes across the sample points.
///
private const int INDEX_VALUES = 3;
///
/// Checks whether two expressions agree at every sample point where both have a value.
///
///
/// A condition of AngouriMath, as in x + 1 provided not x - 1 = 0, is left aside on both sides:
/// the expressions are compared where they have a value.
///
/// One expression.
/// The other expression.
/// What the check found.
public static NumericCheckOutcome AreEqual(Entity left, Entity right) => AreEqual(left, right, []);
///
/// 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.
///
/// One expression.
/// The other expression.
/// The indices which occur freely in the expressions, e.g., n for any integer.
/// What the check found; not possible when an index takes none of the integers tried.
public static NumericCheckOutcome AreEqual(Entity left, Entity right, IReadOnlyList 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, indexValues);
var leftValue = ValueAt(left, assignment);
var rightValue = ValueAt(right, assignment);
if (leftValue is null || rightValue is null)
continue;
validPoints++;
if (!AreClose(leftValue, rightValue, TOLERANCE))
return NumericCheckOutcome.FAILED;
}
return validPoints >= MIN_VALID_POINTS ? NumericCheckOutcome.PASSED : NumericCheckOutcome.NOT_POSSIBLE;
}
///
/// Checks whether one expression is the derivative of another, by a central difference at each sample point.
///
/// The claimed derivative.
/// The function.
/// The variable of the derivative.
/// What the check found.
public static NumericCheckOutcome IsDerivativeOf(Entity derivative, Entity function, Entity.Variable variable)
{
derivative = WithoutCondition(derivative);
function = WithoutCondition(function);
var variables = MathVariables.FreeIn(derivative).Concat(MathVariables.FreeIn(function)).Append(variable).Distinct().OrderBy(free => free.Name, StringComparer.Ordinal).ToArray();
using var precision = MathS.Settings.DecimalPrecisionContext.Set(EContext.ForPrecision(DERIVATIVE_PRECISION));
var validPoints = 0;
for (var point = 0; point < SAMPLE_POINTS; point++)
{
var assignment = SampleAssignment(point, variables);
var at = assignment[variable];
var claimed = ValueAt(derivative, assignment);
var value = ValueAt(function, assignment);
if (claimed is null || value is null)
continue;
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;
}
return validPoints >= MIN_VALID_POINTS ? NumericCheckOutcome.PASSED : NumericCheckOutcome.NOT_POSSIBLE;
}
///
/// 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.
///
///
/// 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.
///
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));
}
///
/// The decimal logarithm of the larger part of a number, roughly, also beyond the range of a double.
///
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;
}
///
/// The values of the variables at one sample point.
///
/// The number of the point, from zero.
/// The variables, in a fixed order.
/// Each variable with its exact value.
public static IReadOnlyDictionary SampleAssignment(int point, IReadOnlyList variables) => SampleAssignment(point, variables, new Dictionary>());
///
/// The values of the variables at one sample point, where the indices of a family of solutions take integers of their sets.
///
/// The number of the point, from zero.
/// The variables, in a fixed order.
/// The indices among the variables.
/// Each variable with its exact value; an index which takes none of the integers tried is left out.
public static IReadOnlyDictionary SampleAssignment(int point, IReadOnlyList variables, IReadOnlyList indices) => SampleAssignment(point, variables, IndexValues(indices));
///
/// The integers each index takes, at most INDEX_VALUES of them.
///
private static Dictionary> IndexValues(IReadOnlyList indices)
{
var values = new Dictionary>(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 SampleAssignment(int point, IReadOnlyList variables, IReadOnlyDictionary> indexValues)
{
var assignment = new Dictionary(variables.Count);
for (var index = 0; index < variables.Count; index++)
{
// An index takes integers of its set, since a family of solutions holds only there:
if (indexValues.TryGetValue(variables[index], out var values))
{
if (values.Count > 0)
assignment[variables[index]] = values[(point + index) % values.Count];
continue;
}
var hundredths = SAMPLE_HUNDREDTHS[(point * 3 + index * 5) % SAMPLE_HUNDREDTHS.Length];
assignment[variables[index]] = Entity.Number.Rational.Create(hundredths, 100);
}
return assignment;
}
private static Dictionary With(IReadOnlyDictionary assignment, Entity.Variable variable, Entity value) => new(assignment) { [variable] = value };
///
/// The value of an expression with its variables replaced, or null when it has none there.
///
/// The expression.
/// The value of each variable.
/// The value, or null for no value, an infinite one, one MathGuards.CheckValueAtPoint refuses, or one AngouriMath cannot evaluate.
public static Entity.Number.Complex? ValueAt(Entity expression, IReadOnlyDictionary assignment)
{
try
{
var substituted = expression;
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 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());
return IsFinite(number) ? number : null;
}
catch (Exception exception) when (exception is not OperationCanceledException)
{
return null;
}
}
private static Entity WithoutCondition(Entity expression) => expression is Entity.Providedf provided ? provided.Expression : expression;
private static bool IsFinite(Entity.Number.Complex number) => IsFinite(number.RealPart.EDecimal) && IsFinite(number.ImaginaryPart.EDecimal);
private static bool IsZero(Entity.Number.Complex number) => number.RealPart.EDecimal.IsZero && number.ImaginaryPart.EDecimal.IsZero;
private static bool IsFinite(EDecimal value) => !value.IsNaN() && !value.IsInfinity();
private static bool AreClose(Entity.Number.Complex left, Entity.Number.Complex right, EDecimal tolerance)
{
var context = EContext.ForPrecision(PRECISION);
var difference = left.RealPart.EDecimal.Subtract(right.RealPart.EDecimal, context).Abs().Add(left.ImaginaryPart.EDecimal.Subtract(right.ImaginaryPart.EDecimal, context).Abs(), context);
var leftSize = left.RealPart.EDecimal.Abs().Add(left.ImaginaryPart.EDecimal.Abs(), context);
var rightSize = right.RealPart.EDecimal.Abs().Add(right.ImaginaryPart.EDecimal.Abs(), context);
//
// Against 0, the tolerance is absolute: an expression whose terms cancel, such as sin(2*x) - 2*sin(x)*cos(x),
// comes only as close as its rounding noise. Between two other values, it is relative, so that tiny values,
// such as those of a formula with the Planck constant, are still told apart:
//
var scale = leftSize.IsZero || rightSize.IsZero ? EDecimal.One : EDecimal.Max(leftSize, rightSize);
return difference.CompareTo(tolerance.Multiply(scale, context)) <= 0;
}
}