From b7b49b2bcd2f63b3555ab17d2b549b1c1614806a Mon Sep 17 00:00:00 2001 From: Rafael Vuijk Date: Fri, 13 Nov 2026 15:06:36 +0000 Subject: [PATCH 1/3] Ask the e-graph whether two expressions are equal MathS.AreEqual(left, right, budget, weakest = Sound, domain = Complex) answers Equal, NotEqual or Unknown. - NotEqual only with a witness: a point where the library's evaluation and an enclosure of every subexpression say both sides are defined, and enclosures of the two values are disjoint (doubles, then fifty digits). The point is looked for first, so no proof is reported over a point that refutes it. - Equal only when both sides land in one e-class. Under weakest = Sound only rules declaring Sound fire; under SoundUnderAssumptions the conditional rules and the canonical-form pass join, the answer names those that merged a class, and a proof the sound rules also make is reported as Sound. - Bounded in steps: a point tried, a match attempt, a node grown. Saturation.Run reports each rule whose application merged two classes. Part of #1251. Co-Authored-By: Claude Opus 5.5 --- Sources/.editorconfig | 3 + .../AngouriMath/Convenience/MathS.Equality.cs | 66 +++++ .../Core/Transformations/EqualityAnswer.cs | 96 +++++++ .../Core/Transformations/EqualityOracle.cs | 228 ++++++++++++++++ .../Core/Transformations/Saturation.cs | 20 +- .../Core/Transformations/AreEqualTest.cs | 251 ++++++++++++++++++ 6 files changed, 659 insertions(+), 5 deletions(-) create mode 100644 Sources/AngouriMath/Convenience/MathS.Equality.cs create mode 100644 Sources/AngouriMath/Core/Transformations/EqualityAnswer.cs create mode 100644 Sources/AngouriMath/Core/Transformations/EqualityOracle.cs create mode 100644 Sources/Tests/UnitTests/Core/Transformations/AreEqualTest.cs diff --git a/Sources/.editorconfig b/Sources/.editorconfig index d40b4ba27..11b4496c9 100644 --- a/Sources/.editorconfig +++ b/Sources/.editorconfig @@ -1093,3 +1093,6 @@ file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed [AngouriMath/Functions/Simplification/ProductsOfMatrices.cs] file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed under MIT.\nDetails: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.\nWebsite: https://am.angouri.org.\n + +[AngouriMath/Convenience/MathS.Equality.cs] +file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed under MIT.\nDetails: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.\nWebsite: https://am.angouri.org.\n diff --git a/Sources/AngouriMath/Convenience/MathS.Equality.cs b/Sources/AngouriMath/Convenience/MathS.Equality.cs new file mode 100644 index 000000000..ad1874626 --- /dev/null +++ b/Sources/AngouriMath/Convenience/MathS.Equality.cs @@ -0,0 +1,66 @@ +// +// Copyright (c) 2019-2026 Angouri. +// AngouriMath is licensed under MIT. +// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md. +// Website: https://am.angouri.org. +// + +using AngouriMath.Core; +using AngouriMath.Core.Budgets; +using AngouriMath.Core.Transformations; + +namespace AngouriMath +{ + partial class MathS + { + /// + /// Whether and are equal: proved by the + /// rewrite rules over one e-graph, refuted at a point, or neither within + /// . + /// + /// One side. + /// The other. + /// + /// What the question may spend. counts work -- a point + /// tried, a rule's match attempt, a node the graph grows by -- so the same question under + /// the same steps gets the same answer on any machine; a + /// makes it depend on the machine, and says when it + /// did. , where set, overrides this. + /// + /// + /// The weakest soundness a proof may rest on. , the default, + /// admits only rules that hold with no side condition; a proof that needs more is + /// . + /// admits the conditional rules and the canonical-form pass as well, and names those it + /// used in . + /// + /// + /// , the default, or : where the + /// variables range, and so where a witness may be looked for. + /// + /// + /// only with a proof; + /// only with a point at which both sides are + /// defined and enclosures of their values are disjoint; + /// otherwise -- which is not "unequal". + /// + /// + /// + /// Not (left - right).Simplify() == 0. A simplification picks one representative + /// per input by cost, and two equal inputs can settle on different ones; a graph holding + /// both merges their classes whether or not an extraction would agree. And a + /// simplification has no third answer: a difference that does not simplify to zero is + /// read as "unequal" by whoever compares it. + /// + /// + /// The rules are the safe ceiling's, which do not enlarge; zero-equivalence is + /// undecidable over this language, so is an + /// answer this gives often and honestly. + /// #1251 + /// + /// + public static EqualityAnswer AreEqual(Entity left, Entity right, WorkBudget budget, + Soundness weakest = Soundness.Sound, Domain domain = Domain.Complex) + => EqualityOracle.Ask(left, right, budget, weakest, domain); + } +} diff --git a/Sources/AngouriMath/Core/Transformations/EqualityAnswer.cs b/Sources/AngouriMath/Core/Transformations/EqualityAnswer.cs new file mode 100644 index 000000000..18614a8b3 --- /dev/null +++ b/Sources/AngouriMath/Core/Transformations/EqualityAnswer.cs @@ -0,0 +1,96 @@ +// +// Copyright (c) 2019-2026 Angouri. +// AngouriMath is licensed under MIT. +// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md. +// Website: https://am.angouri.org. +// + +using System; +using System.Collections.Generic; +using System.Linq; +using AngouriMath.Core.Budgets; + +namespace AngouriMath.Core.Transformations +{ + /// What could establish about two expressions. + public enum EqualityVerdict + { + /// + /// Neither shown: no proof within the budget and no point at which the two differ. Says + /// nothing about whether they are equal. + /// + Unknown, + + /// Proved equal by rewrite rules; see . + Equal, + + /// + /// Shown to differ at , where both are defined and + /// enclosures of their values are disjoint. Never a failure to prove equality. + /// + NotEqual, + } + + /// + /// The answer of : a verdict, what it rests on, and what it cost. + /// + /// + /// What claims. At every assignment of the free + /// variables in the domain asked at which both sides have a value, the values agree, provided + /// that each rewrite the proof used holds as its declares. A + /// justification rests on nothing else. A + /// one rests in addition on the side + /// conditions of the steps named in , which are not data the library + /// can check: a caller who needs an unconditional answer asks for + /// and gets instead. + /// + public sealed record EqualityAnswer + { + internal EqualityAnswer(EqualityVerdict verdict, Soundness? justification, + IReadOnlyList assumptions, IReadOnlyDictionary? witness, + BudgetOutcome budget) + { + Verdict = verdict; + Justification = justification; + Assumptions = assumptions; + Witness = witness; + Budget = budget; + } + + /// Equal, not equal, or not shown either way. + public EqualityVerdict Verdict { get; } + + /// + /// For , the weakest soundness among the steps the + /// proof may rest on. for the other verdicts. + /// + public Soundness? Justification { get; } + + /// + /// The conditional steps — rules declaring , + /// and the canonical-form pass — that joined two classes while the proof was sought: a + /// superset of those it needs. Empty for a proof. + /// + public IReadOnlyList Assumptions { get; } + + /// + /// For , the point at which the two sides differ: + /// a value for each free variable. Empty where neither side has one. + /// + public IReadOnlyDictionary? Witness { get; } + + /// What the question spent, and which ceiling, if any, stopped it. + public BudgetOutcome Budget { get; } + + /// + public override string ToString() + => Verdict switch + { + EqualityVerdict.Equal when Assumptions.Count == 0 => $"Equal ({Justification})", + EqualityVerdict.Equal => $"Equal ({Justification}: {string.Join(", ", Assumptions)})", + EqualityVerdict.NotEqual => "NotEqual at " + + (Witness!.Count == 0 ? "the constants" : string.Join(", ", Witness.Select(p => $"{p.Key} = {p.Value}"))), + _ => $"Unknown ({Budget})", + }; + } +} diff --git a/Sources/AngouriMath/Core/Transformations/EqualityOracle.cs b/Sources/AngouriMath/Core/Transformations/EqualityOracle.cs new file mode 100644 index 000000000..4cce5f546 --- /dev/null +++ b/Sources/AngouriMath/Core/Transformations/EqualityOracle.cs @@ -0,0 +1,228 @@ +// +// Copyright (c) 2019-2026 Angouri. +// AngouriMath is licensed under MIT. +// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md. +// Website: https://am.angouri.org. +// + +using System; +using System.Collections.Generic; +using System.Linq; +using AngouriMath.Core.Budgets; +using AngouriMath.Core.Transformations.Matching; +using AngouriMath.Numerics; +using static AngouriMath.Entity; +using static AngouriMath.Entity.Number; + +namespace AngouriMath.Core.Transformations +{ + /// + /// The e-graph asked whether two expressions are equal, with a witness for the other answer. + /// https://github.com/asc-community/AngouriMath/issues/1251 + /// + /// + /// + /// Refute first, then prove. A point where both sides are defined and their enclosures + /// are disjoint settles the question for good and costs a dozen evaluations; a proof costs a + /// saturation. Looking for the point first also means no proof is ever reported over a point + /// the sampling found against it — so a rule that declares more soundness than it has + /// surfaces as with a witness, never as a wrong + /// , wherever the sampled points reach it. + /// + /// + /// Why the proof is one graph and not two canonical forms. See + /// : two sides canonicalised apart meet only where the + /// rules are confluent; inserted into one graph, they meet wherever the rules reach. + /// + /// + internal static class EqualityOracle + { + private const string Where = "AreEqual"; + + /// The canonical-form pass's name in . + internal const string CanonicalizationStep = "canonicalization"; + + /// + /// The rules whose is + /// at the safe growth ceiling, built once. + /// + internal static IReadOnlyList SoundRules => soundRules.Value; + + [ConstantField] + private static readonly Lazy> soundRules + = new(() => Saturation.SafeRules.Where(rule => rule.Soundness == Soundness.Sound).ToList()); + + internal static EqualityAnswer Ask(Entity left, Entity right, WorkBudget budget, Soundness weakest, Domain domain) + { + if (left is null) throw new ArgumentNullException(nameof(left)); + if (right is null) throw new ArgumentNullException(nameof(right)); + if (budget is null) throw new ArgumentNullException(nameof(budget)); + if (weakest is not (Soundness.Sound or Soundness.SoundUnderAssumptions)) + throw new ArgumentOutOfRangeException(nameof(weakest), weakest, + "A heuristic step proves nothing, so it cannot justify an equality."); + if (domain is not (Domain.Complex or Domain.Real)) + throw new ArgumentOutOfRangeException(nameof(domain), domain, + "Equality is asked over the complex or the real numbers."); + + var ledger = BudgetLedger.For(Where, budget); + try + { + if (left.Equals(right)) + return Equal(Soundness.Sound, Array.Empty(), ledger); + + if (FindWitness(left, right, domain, ledger) is { } witness) + return new(EqualityVerdict.NotEqual, null, Array.Empty(), witness, ledger.Outcome()); + + if (weakest == Soundness.Sound) + return Prove(left, right, SoundRules, canonicalize: false, ledger, out _) + ? Equal(Soundness.Sound, Array.Empty(), ledger) + : Unknown(ledger); + + if (!Prove(left, right, Saturation.SafeRules, canonicalize: true, ledger, out var conditional)) + return Unknown(ledger); + if (conditional.Count == 0) + return Equal(Soundness.Sound, Array.Empty(), ledger); + // Proved, but a conditional step may have done it, or only been there when it was + // done. The sound rules alone, on what the budget has left, tell the two apart. + return Prove(left, right, SoundRules, canonicalize: false, ledger, out _) + ? Equal(Soundness.Sound, Array.Empty(), ledger) + : Equal(Soundness.SoundUnderAssumptions, conditional, ledger); + } + finally + { + ledger.Report(); + } + } + + private static EqualityAnswer Equal(Soundness justification, IReadOnlyList assumptions, BudgetLedger ledger) + => new(EqualityVerdict.Equal, justification, assumptions, null, ledger.Outcome()); + + private static EqualityAnswer Unknown(BudgetLedger ledger) + => new(EqualityVerdict.Unknown, null, Array.Empty(), null, ledger.Outcome()); + + /// + /// Whether join and + /// in one graph, and the conditional steps that joined any two + /// classes on the way. + /// + private static bool Prove(Entity left, Entity right, IReadOnlyList rules, + bool canonicalize, BudgetLedger ledger, out IReadOnlyList conditional) + { + var steps = new SortedSet(StringComparer.Ordinal); + conditional = Array.Empty(); + if (ledger.Exhausted) return false; + + var graph = new EGraph(); + var a = graph.AddEntity(left); + var b = graph.AddEntity(right); + // The graph does not sort a commutative operand pair or flatten a nested sum -- the + // rules that do build their replacement in code, so no ceiling admits them -- and the + // canonical-form pass does both. It joins each side to its own canonical form, as one + // more conditional step: the pass declares SoundUnderAssumptions. + if (canonicalize) + foreach (var (side, id) in new[] { (left, a), (right, b) }) + { + if (!ledger.Spend()) return false; + var canonical = Transformation.Canonicalization.ApplyOrKeep(side); + if (!canonical.Equals(side) && graph.Union(id, graph.AddEntity(canonical))) + steps.Add(CanonicalizationStep); + } + graph.Rebuild(); + + if (graph.Find(a) != graph.Find(b)) + Saturation.Run(graph, rules, ledger, CostModel.Default.Cost, + settled: () => graph.Find(a) == graph.Find(b), + merged: rule => + { + if (rule.Soundness != Soundness.Sound) steps.Add(rule.Name); + }); + + conditional = steps.ToList(); + return graph.Find(a) == graph.Find(b); + } + + /// + /// Values the variables are given in turn: irregular, so that no point sits on a pole or a + /// cut by the coincidence of a small integer, of both signs, and off the real line. + /// + [ConstantField] + private static readonly Complex[] RealValues = + { + Rational.Create(7, 5), Rational.Create(-3, 7), Rational.Create(13, 4), + Rational.Create(-11, 5), Rational.Create(2, 9), Rational.Create(-5, 3), + }; + + [ConstantField] + private static readonly Complex[] ComplexValues = RealValues.Concat(new[] + { + Complex.Create(Rational.Create(2, 3), Rational.Create(5, 4)), + Complex.Create(Rational.Create(-7, 6), Rational.Create(1, 3)), + Complex.Create(Rational.Create(1, 5), Rational.Create(-9, 7)), + // Past pi off the real line, where a logarithm's principal branch stops undoing + // an exponential: ln(e^x) and x part only once |Im x| > pi. + Complex.Create(Rational.Create(-2, 7), Rational.Create(19, 5)), + }).ToArray(); + + /// How many points are tried, each charged one step. + internal const int Points = 12; + + /// + /// A point at which both sides are defined and provably differ, or . + /// + /// + /// "Defined" is asked three ways, and all three must say yes, because a witness is a claim + /// that two values exist: the library's own evaluation gives a finite number, and an + /// enclosure exists for every subexpression, not only for the whole. The second matters + /// because the enclosures take a product with an exact zero to zero whatever the other + /// factor is, so 0 * (1/x) at x = 0 has an enclosure and no value. "Differ" + /// is an enclosure of the difference that excludes zero -- doubles first, fifty digits + /// where the doubles cannot tell -- never a difference that merely looks large. + /// + private static IReadOnlyDictionary? FindWitness(Entity left, Entity right, Domain domain, BudgetLedger ledger) + { + var variables = left.Vars.Concat(right.Vars).Distinct().OrderBy(v => v.Name, StringComparer.Ordinal).ToList(); + var pool = domain == Domain.Real ? RealValues : ComplexValues; + var points = variables.Count == 0 ? 1 : Points; + for (var i = 0; i < points; i++) + { + if (!ledger.Spend()) return null; + var point = new Dictionary(); + for (var j = 0; j < variables.Count; j++) + point[variables[j]] = pool[(i + 5 * j) % pool.Length]; + var l = variables.Count == 0 ? left : left.Substitute(point); + var r = variables.Count == 0 ? right : right.Substitute(point); + if (Differ(l, r, domain)) return point; + } + return null; + } + + private static bool Differ(Entity left, Entity right, Domain domain) + { + if (Enclosure(left, domain) is not { } l || Enclosure(right, domain) is not { } r) + return false; + if (IntervalEvaluation.Agree(l, r, 0) is { } agree) + return !agree; + const int digits = 50; + return PreciseEvaluation.Of(left, digits) is { } pl && PreciseEvaluation.Of(right, digits) is { } pr + && PreciseEvaluation.Agree(pl, pr, 0) == false; + } + + /// The enclosure of a variable-free expression that is defined, or null. + private static ComplexInterval? Enclosure(Entity expr, Domain domain) + { + if (expr.Evaled is not Complex value || value.IsNaN || !value.IsFinite) + return null; + if (domain == Domain.Real && value is not Real) + return null; + foreach (var node in expr.Nodes) + { + if (node is Complex) continue; + if (IntervalEvaluation.Of(node) is not { } enclosure) + return null; + if (domain == Domain.Real && !enclosure.IsReal) + return null; + } + return IntervalEvaluation.Of(expr); + } + } +} diff --git a/Sources/AngouriMath/Core/Transformations/Saturation.cs b/Sources/AngouriMath/Core/Transformations/Saturation.cs index efd6b52be..71c36041b 100644 --- a/Sources/AngouriMath/Core/Transformations/Saturation.cs +++ b/Sources/AngouriMath/Core/Transformations/Saturation.cs @@ -119,8 +119,14 @@ private static readonly Lazy> safeRules /// third (#1200). /// passes nothing: it needs a union, not an extraction. /// + /// + /// Told of every rule whose application joined two classes that were apart, so that a + /// caller can say which rules an equality it reads off the graph may rest on: every union + /// the graph holds is one of these or a congruence that follows from them. + /// internal static bool Run(EGraph graph, IReadOnlyList rules, - BudgetLedger ledger, Func witnessCost, Func? settled = null) + BudgetLedger ledger, Func witnessCost, Func? settled = null, + Action? merged = null) { var chargedNodes = graph.NodeCount; bool ChargeGrowthSinceLastCall() @@ -137,7 +143,7 @@ bool ChargeGrowthSinceLastCall() var saturated = false; while (!saturated && !ledger.Exhausted) { - var merged = false; + var unioned = false; foreach (var id in graph.Classes.ToList()) { if (ledger.Exhausted) break; @@ -150,7 +156,7 @@ bool ChargeGrowthSinceLastCall() // // A union later in this same sweep can add a node type this set does not have, // so a rule can be skipped in a pass where it had just become applicable. That - // costs nothing: a union is exactly what sets `merged`, so there is another + // costs nothing: a union is exactly what sets `unioned`, so there is another // pass, and the set is gathered again there. var held = new HashSet(); foreach (var node in graph.NodesOf(id)) held.Add(graph.RuntimeType(node)); @@ -207,7 +213,11 @@ bool TryTerm(out Entity value) if (rewritten is null || rewritten.Equals(t)) continue; other = graph.AddEntity(rewritten); } - if (graph.Union(id, other)) merged = true; + if (graph.Union(id, other)) + { + unioned = true; + merged?.Invoke(rule); + } } // What the sweep grew, charged after it rather than before the next class's, @@ -219,7 +229,7 @@ bool TryTerm(out Entity value) // congruent -- a round of it is work, and it had no ledger interaction anywhere. if (!ledger.Spend()) break; graph.Rebuild(); - if (!merged) saturated = true; + if (!unioned) saturated = true; else if (settled is not null && settled()) break; } return saturated; diff --git a/Sources/Tests/UnitTests/Core/Transformations/AreEqualTest.cs b/Sources/Tests/UnitTests/Core/Transformations/AreEqualTest.cs new file mode 100644 index 000000000..c905ef1d4 --- /dev/null +++ b/Sources/Tests/UnitTests/Core/Transformations/AreEqualTest.cs @@ -0,0 +1,251 @@ +// +// Copyright (c) 2019-2026 Angouri. +// AngouriMath is licensed under MIT. +// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md. +// Website: https://am.angouri.org. +// + +using System; +using System.Collections.Generic; +using System.Linq; +using AngouriMath.Core; +using AngouriMath.Core.Budgets; +using AngouriMath.Core.Transformations; +using AngouriMath.Extensions; +using AngouriMath.Numerics; +using Xunit; +using static AngouriMath.Entity; +using static AngouriMath.Entity.Number; + +namespace AngouriMath.Tests.Core.Transformations +{ + /// + /// : the e-graph asked whether two expressions are equal. + /// https://github.com/asc-community/AngouriMath/issues/1251 + /// + [Trait("Area", "Core")] + public sealed class AreEqualTest + { + /// Steps only: an answer must not depend on the machine running the test. + private static readonly WorkBudget Budget = new() { Steps = 20_000 }; + + private static EqualityAnswer Ask(string left, string right, + Soundness weakest = Soundness.Sound, Domain domain = Domain.Complex) + => MathS.AreEqual(left.ToEntity(), right.ToEntity(), Budget, weakest, domain); + + [Theory] + [InlineData("x + 0", "x")] + [InlineData("x * 1", "x")] + [InlineData("x - x", "0")] + [InlineData("2 * x + 3 * x", "5 * x")] + [InlineData("(x + y) * (x - y)", "x ^ 2 - y ^ 2")] + [InlineData("sin(x) ^ 2 + cos(x) ^ 2", "1")] + [InlineData("a * b + a * c", "a * (b + c)")] + [InlineData("2 ^ (1/2)", "sqrt(2)")] + public void AnIdentityTheSoundRulesReachIsEqualUnconditionally(string left, string right) + { + var answer = Ask(left, right); + Assert.Equal(EqualityVerdict.Equal, answer.Verdict); + Assert.Equal(Soundness.Sound, answer.Justification); + Assert.Empty(answer.Assumptions); + Assert.Null(answer.Witness); + } + + /// + /// An identity whose proof needs a step that declares + /// is + /// to a caller who asked for an unconditional proof, and + /// naming the steps to a caller who admits them. Commutativity is here because the graph + /// does not sort operands and the pass that does declares the weaker soundness. + /// + [Theory] + [InlineData("x + y", "y + x", "canonicalization")] + [InlineData("x * y", "y * x", "canonicalization")] + [InlineData("tan(x)", "sin(x) / cos(x)", "sine-over-cosine-is-the-tangent")] + [InlineData("exp(x + y)", "exp(x) * exp(y)", "two-powers-of-one-base-multiply-by-adding-exponents")] + [InlineData("x ^ 2 * x ^ 3", "x ^ 5", "two-powers-of-one-base-multiply-by-adding-exponents")] + [InlineData("2 * sqrt(2) * sqrt(3)", "2 * sqrt(6)", "a-numeric-factor-floats-out-of-a-product-of-functions")] + public void AConditionalProofIsEqualOnlyWhereItsConditionIsAdmitted(string left, string right, string step) + { + Assert.Equal(EqualityVerdict.Unknown, Ask(left, right).Verdict); + + var admitted = Ask(left, right, Soundness.SoundUnderAssumptions); + Assert.Equal(EqualityVerdict.Equal, admitted.Verdict); + Assert.Equal(Soundness.SoundUnderAssumptions, admitted.Justification); + Assert.Contains(admitted.Assumptions, name => name.StartsWith(step, StringComparison.Ordinal)); + } + + /// + /// Admitting conditional rules does not weaken a proof the sound rules make alone: the + /// justification is the weakest the answer needs, not the weakest that was admitted. + /// + [Fact] + public void ASoundProofStaysSoundWhenConditionalRulesAreAdmitted() + { + var answer = Ask("(x + y) * (x - y)", "x ^ 2 - y ^ 2", Soundness.SoundUnderAssumptions); + Assert.Equal(EqualityVerdict.Equal, answer.Verdict); + Assert.Equal(Soundness.Sound, answer.Justification); + Assert.Empty(answer.Assumptions); + } + + [Theory] + [InlineData("x + 1", "x")] + [InlineData("x", "y")] + [InlineData("sqrt(x ^ 2)", "x")] + [InlineData("(x ^ 2) ^ (1/2)", "x")] + [InlineData("arcsin(sin(x))", "x")] + [InlineData("pi", "3.14159")] + // False off the real line, and each a rule some system ships unguarded. + [InlineData("sqrt(x ^ 2)", "abs(x)")] + [InlineData("ln(x * y)", "ln(x) + ln(y)")] + [InlineData("sqrt(x) * sqrt(y)", "sqrt(x * y)")] + [InlineData("ln(e ^ x)", "x")] + public void ANonIdentityIsNotEqualWithAWitnessThatChecks(string left, string right) + { + foreach (var weakest in new[] { Soundness.Sound, Soundness.SoundUnderAssumptions }) + { + var answer = Ask(left, right, weakest); + Assert.Equal(EqualityVerdict.NotEqual, answer.Verdict); + Assert.NotNull(answer.Witness); + AssertDiffersAt(left.ToEntity(), right.ToEntity(), answer.Witness!); + } + } + + /// + /// The domain asked decides where a witness may be: these hold over the reals and fail + /// off them, so over the reals the answer is -- + /// not proved, and not refuted with a point the caller did not ask about. + /// + [Theory] + [InlineData("sqrt(x ^ 2)", "abs(x)")] + [InlineData("ln(e ^ x)", "x")] + public void AWitnessIsLookedForOnlyWhereTheVariablesRange(string left, string right) + { + Assert.Equal(EqualityVerdict.NotEqual, Ask(left, right).Verdict); + Assert.Equal(EqualityVerdict.Unknown, Ask(left, right, domain: Domain.Real).Verdict); + } + + /// + /// Identities the safe rules do not reach. Each is true wherever both sides are defined + /// (and e ^ ln(x) everywhere they are), so + /// would be wrong; is the honest answer, and one of + /// these turning is an improvement to record. + /// + [Theory] + [InlineData("(x + 1) ^ 2", "x ^ 2 + 2 * x + 1")] + [InlineData("1 / x + 1 / y", "(x + y) / (x * y)")] + [InlineData("sin(2 * x)", "2 * sin(x) * cos(x)")] + [InlineData("e ^ ln(x)", "x")] + [InlineData("x / x", "1")] + public void AnIdentityBeyondTheRulesIsUnknown(string left, string right) + { + foreach (var weakest in new[] { Soundness.Sound, Soundness.SoundUnderAssumptions }) + foreach (var domain in new[] { Domain.Complex, Domain.Real }) + { + var answer = Ask(left, right, weakest, domain); + Assert.Equal(EqualityVerdict.Unknown, answer.Verdict); + Assert.Null(answer.Justification); + Assert.Null(answer.Witness); + } + } + + /// + /// Under no steps nothing is tried, and the answer says the ceiling stopped it rather + /// than reading as a negative. + /// + [Fact] + public void UnderNoBudgetTheAnswerIsUnknownAndSaysWhy() + { + var answer = MathS.AreEqual("x + y".ToEntity(), "y + x".ToEntity(), new WorkBudget { Steps = 0 }, + Soundness.SoundUnderAssumptions); + Assert.Equal(EqualityVerdict.Unknown, answer.Verdict); + Assert.False(answer.Budget.Completed); + Assert.True(answer.Budget.IsDeterministic); + } + + /// The budget is work, so the same question costs the same steps every time. + [Theory] + [InlineData("(x + y) * (x - y)", "x ^ 2 - y ^ 2")] + [InlineData("(x + 1) ^ 2", "x ^ 2 + 2 * x + 1")] + public void TheSameQuestionCostsTheSameSteps(string left, string right) + { + var first = Ask(left, right, Soundness.SoundUnderAssumptions); + var second = Ask(left, right, Soundness.SoundUnderAssumptions); + Assert.Equal(first.Budget.Steps, second.Budget.Steps); + Assert.Equal(first.Verdict, second.Verdict); + + // And a ceiling below what it spent stops it at the ceiling, not after it. + var starved = MathS.AreEqual(left.ToEntity(), right.ToEntity(), + new WorkBudget { Steps = first.Budget.Steps / 2 }, Soundness.SoundUnderAssumptions); + Assert.False(starved.Budget.Completed); + Assert.True(starved.Budget.Steps <= first.Budget.Steps / 2 + 1); + } + + [Fact] + public void AHeuristicCannotJustifyAnEquality() + => Assert.Throws( + () => MathS.AreEqual("x".ToEntity(), "x".ToEntity(), Budget, Soundness.Heuristic)); + + /// + /// None of the answers above is wrong, checked against evaluation at points the oracle + /// does not sample: positive, negative, zero and off the real line. An + /// must agree wherever both sides are defined; a + /// is checked at its own witness by + /// . + /// + [Theory] + [InlineData("x + 0", "x")] + [InlineData("x - x", "0")] + [InlineData("2 * x + 3 * x", "5 * x")] + [InlineData("(x + y) * (x - y)", "x ^ 2 - y ^ 2")] + [InlineData("sin(x) ^ 2 + cos(x) ^ 2", "1")] + [InlineData("a * b + a * c", "a * (b + c)")] + [InlineData("x + y", "y + x")] + [InlineData("tan(x)", "sin(x) / cos(x)")] + [InlineData("exp(x + y)", "exp(x) * exp(y)")] + [InlineData("x ^ 2 * x ^ 3", "x ^ 5")] + public void AnEqualAnswerAgreesWithEvaluation(string left, string right) + { + var l = left.ToEntity(); + var r = right.ToEntity(); + Assert.Equal(EqualityVerdict.Equal, Ask(left, right, Soundness.SoundUnderAssumptions).Verdict); + + var values = new Entity[] + { + Rational.Create(5, 7), Rational.Create(-9, 4), 0, 3, + Complex.Create(Rational.Create(3, 2), Rational.Create(2, 5)), + Complex.Create(Rational.Create(-1, 3), Rational.Create(-7, 4)), + Complex.Create(Rational.Create(1, 9), Rational.Create(11, 2)), + }; + var variables = l.Vars.Concat(r.Vars).Distinct().ToList(); + var compared = 0; + for (var i = 0; i < values.Length; i++) + { + var point = new Dictionary(); + for (var j = 0; j < variables.Count; j++) + point[variables[j]] = values[(i + 3 * j) % values.Length]; + if (IntervalEvaluation.Of(l.Substitute(point)) is not { } lv + || IntervalEvaluation.Of(r.Substitute(point)) is not { } rv) + continue; + compared++; + Assert.NotEqual(false, IntervalEvaluation.Agree(lv, rv, 1e-12)); + } + Assert.True(compared >= 4, $"only {compared} points had a value on both sides"); + } + + /// + /// A witness checked by a route the oracle does not take: the library's own numeric + /// evaluation of each side, which must be finite and differ by more than rounding. + /// + private static void AssertDiffersAt(Entity left, Entity right, IReadOnlyDictionary witness) + { + var l = left.Substitute(witness).EvalNumerical(); + var r = right.Substitute(witness).EvalNumerical(); + Assert.True(l.IsFinite && r.IsFinite, $"{left} = {l}, {right} = {r} at the witness"); + var (ln, rn) = (l.ToNumerics(), r.ToNumerics()); + var difference = System.Numerics.Complex.Abs(ln - rn); + Assert.True(difference > 1e-9 * Math.Max(1, Math.Max(ln.Magnitude, rn.Magnitude)), + $"{left} = {l} and {right} = {r} do not differ"); + } + } +} From 73288d82d4c59a9c89bb5fab365aff3a61a8e002 Mon Sep 17 00:00:00 2001 From: Rafael Vuijk Date: Sun, 15 Nov 2026 00:45:20 +0000 Subject: [PATCH 2/3] Reorder a sum or a product as a sound step when asking for equality The e-graph neither sorts a commutative pair nor flattens a nested chain, and the pass that does, CanonicalOrderExact, also groups like terms and so declares SoundUnderAssumptions. x + y = y + x was therefore Unknown to a caller asking for an unconditional proof. Two oracle-only steps, declared Sound, flatten a Sumf chain or a Mulf chain (differences and quotients stay operands) and rebuild it in EntityOrder.Canonical order, grouping nothing. Commutativity and associativity hold for numbers with no side condition, and a name is a number of the domain asked. A chain is left alone where an operand holds a matrix, a transpose, a set, a statement, a lambda or an application, or where a link is read over a narrower codomain; a question with any matrix or matrix operation in it gets neither step, since a name beside a transpose may be a matrix (#2147). Simplify and every rule set are untouched. Records the public surface #1251 adds in PublicApi.txt, and points CanonicalForm.md's "not a decision procedure for equality" at MathS.AreEqual. Part of #1251. Co-Authored-By: Claude Opus 5.5 --- .../AngouriMath/Convenience/MathS.Equality.cs | 7 +- .../Core/Transformations/EqualityOracle.cs | 158 +++++++++++++++++- .../Docs/Contributing/CanonicalForm.md | 22 +++ Sources/Tests/UnitTests/Common/PublicApi.txt | 19 +++ .../Core/Transformations/AreEqualTest.cs | 123 +++++++++++++- 5 files changed, 315 insertions(+), 14 deletions(-) diff --git a/Sources/AngouriMath/Convenience/MathS.Equality.cs b/Sources/AngouriMath/Convenience/MathS.Equality.cs index ad1874626..0d3ad6880 100644 --- a/Sources/AngouriMath/Convenience/MathS.Equality.cs +++ b/Sources/AngouriMath/Convenience/MathS.Equality.cs @@ -29,14 +29,17 @@ partial class MathS /// /// /// The weakest soundness a proof may rest on. , the default, - /// admits only rules that hold with no side condition; a proof that needs more is + /// admits only rules that hold with no side condition -- reordering the terms of a sum or + /// the factors of a product among them -- and a proof that needs more is /// . /// admits the conditional rules and the canonical-form pass as well, and names those it /// used in . /// /// /// , the default, or : where the - /// variables range, and so where a witness may be looked for. + /// variables range, and so where a witness may be looked for. A name is a number here, so + /// a * b and b * a are equal; a question with a matrix or a matrix operation + /// anywhere in it has no product reordered, since a name in it may stand for a matrix. /// /// /// only with a proof; diff --git a/Sources/AngouriMath/Core/Transformations/EqualityOracle.cs b/Sources/AngouriMath/Core/Transformations/EqualityOracle.cs index 4cce5f546..656cf9a83 100644 --- a/Sources/AngouriMath/Core/Transformations/EqualityOracle.cs +++ b/Sources/AngouriMath/Core/Transformations/EqualityOracle.cs @@ -42,16 +42,155 @@ internal static class EqualityOracle /// The canonical-form pass's name in . internal const string CanonicalizationStep = "canonicalization"; + /// + /// Commutativity and associativity of addition and of multiplication, as two + /// steps: a sum chain and a product chain each put into + /// one order, with nothing grouped, folded or rewritten. + /// + /// + /// + /// Why these are not RewriteRules.CanonicalOrderExact. That set sorts and + /// also groups -- x + x becomes 2 x, a quotient is read as a product + /// with a negative power -- and grouping is what makes it + /// . A reordering alone needs no condition, + /// and the e-graph has none: it does not sort a commutative pair or flatten a nested + /// chain. These belong to this oracle only and run nowhere else, so neither + /// Simplify nor any rule set's output moves. + /// + /// + /// Why they are sound. The variables range over the complex numbers, or the reals, + /// as 's domain says, and addition and multiplication + /// there are commutative and associative with no side condition. Only + /// and chains are read: a difference or a quotient is an operand, never + /// flattened, so no subtraction is read as adding a negation. The order is + /// , which is total, so two writings of one chain sort + /// to the same tree and meet by hash-consing. A chain is left alone (the step declines) + /// where an operand may be something other than a number -- see + /// -- because a matrix product does not commute; and a + /// question with a matrix anywhere in it does not get these steps at all + /// (), since the library reads a name beside a transpose as + /// possibly a matrix (#2147) + /// and that name may be multiplied elsewhere in the same question. + /// + /// + internal static IReadOnlyList OperandOrder { get; } = new[] + { + new MatchedRule( + "the-terms-of-a-sum-are-reordered", + MatchPattern.Any("x"), + (node, _) => Reordered(node, static (a, b) => new Sumf(a, b)), + Soundness.Sound, + RewriteRuleGrowth.Rearranges, + description: "a + (b + c) = (c + a) + b, and every other order and grouping of one sum"), + new MatchedRule( + "the-factors-of-a-product-are-reordered", + MatchPattern.Any("x"), + (node, _) => Reordered(node, static (a, b) => new Mulf(a, b)), + Soundness.Sound, + RewriteRuleGrowth.Rearranges, + description: "a * (b * c) = (c * a) * b, for numbers, and every other order and grouping of one product"), + }; + /// /// The rules whose is - /// at the safe growth ceiling, built once. + /// at the safe growth ceiling, and , built once. /// internal static IReadOnlyList SoundRules => soundRules.Value; [ConstantField] private static readonly Lazy> soundRules + = new(() => Saturation.SafeRules.Where(rule => rule.Soundness == Soundness.Sound) + .Concat(OperandOrder).ToList()); + + /// + /// without , for a question in which + /// something may be a matrix: see . + /// + private static IReadOnlyList SoundRulesWithoutOrder => soundRulesWithoutOrder.Value; + + [ConstantField] + private static readonly Lazy> soundRulesWithoutOrder = new(() => Saturation.SafeRules.Where(rule => rule.Soundness == Soundness.Sound).ToList()); + /// + /// and , built once. + /// + private static IReadOnlyList AdmittedRules => admittedRules.Value; + + [ConstantField] + private static readonly Lazy> admittedRules + = new(() => Saturation.SafeRules.Concat(OperandOrder).ToList()); + + /// + /// The chain rooted at , flattened through nested + /// nodes only and rebuilt in + /// order, grouped to the left -- or itself, which declines, where + /// it is already in that order or an operand may not commute. + /// + private static Entity Reordered(Entity node, Func build) where TChain : Entity + { + // The e-matcher hands over the class's cheapest member, which need not be the node + // type the pattern found in the class. + if (node is not TChain || !ReadByDefault(node)) return node; + var operands = new List(); + var pending = new Stack(); + pending.Push(node); + while (pending.Count > 0) + { + var next = pending.Pop(); + // A link read over a narrower codomain than its own is an operand: rebuilding it + // would drop the reading. + if (next is TChain && ReadByDefault(next)) + { + // Right child first, so the left one is popped first: the written order. + pending.Push(next.DirectChildren[1]); + pending.Push(next.DirectChildren[0]); + } + else + { + if (MayNotCommute(next)) return node; + operands.Add(next); + } + } + operands.Sort(EntityOrder.Canonical); + var rebuilt = operands[0]; + for (var i = 1; i < operands.Count; i++) + rebuilt = build(rebuilt, operands[i]); + return rebuilt.Equals(node) ? node : rebuilt; + } + + private static bool ReadByDefault(Entity link) => link.Codomain == link.DefaultCodomain; + + /// + /// Whether may denote something addition or multiplication + /// does not commute over, or that is not a number at all: a matrix, a transpose (whose + /// argument the library reads as possibly a matrix), a set, a truth value, a function, + /// or an application of one whose value nothing says is a number. + /// + /// + /// Any such node anywhere in the operand, not only at its root. Wider than it has to be + /// -- a determinant is a number, and a sum of matrices commutes -- because a decline costs + /// a proof and a wrong costs the answer. + /// + private static bool MayNotCommute(Entity operand) + { + foreach (var node in operand.Nodes) + if (node is Matrix or Transposef or Set or Statement or Lambda or Application) + return true; + return false; + } + + /// + /// Whether a matrix, or a matrix operation, occurs anywhere in . + /// + private static bool MayHoldAMatrix(Entity expr) + { + foreach (var node in expr.Nodes) + if (node is Matrix or Transposef or Determinantf or Tracef or MatrixEntryf) + return true; + return false; + } + internal static EqualityAnswer Ask(Entity left, Entity right, WorkBudget budget, Soundness weakest, Domain domain) { if (left is null) throw new ArgumentNullException(nameof(left)); @@ -73,18 +212,21 @@ internal static EqualityAnswer Ask(Entity left, Entity right, WorkBudget budget, if (FindWitness(left, right, domain, ledger) is { } witness) return new(EqualityVerdict.NotEqual, null, Array.Empty(), witness, ledger.Outcome()); + var matrices = MayHoldAMatrix(left) || MayHoldAMatrix(right); + var sound = matrices ? SoundRulesWithoutOrder : SoundRules; if (weakest == Soundness.Sound) - return Prove(left, right, SoundRules, canonicalize: false, ledger, out _) + return Prove(left, right, sound, canonicalize: false, ledger, out _) ? Equal(Soundness.Sound, Array.Empty(), ledger) : Unknown(ledger); - if (!Prove(left, right, Saturation.SafeRules, canonicalize: true, ledger, out var conditional)) + var admitted = matrices ? Saturation.SafeRules : AdmittedRules; + if (!Prove(left, right, admitted, canonicalize: true, ledger, out var conditional)) return Unknown(ledger); if (conditional.Count == 0) return Equal(Soundness.Sound, Array.Empty(), ledger); // Proved, but a conditional step may have done it, or only been there when it was // done. The sound rules alone, on what the budget has left, tell the two apart. - return Prove(left, right, SoundRules, canonicalize: false, ledger, out _) + return Prove(left, right, sound, canonicalize: false, ledger, out _) ? Equal(Soundness.Sound, Array.Empty(), ledger) : Equal(Soundness.SoundUnderAssumptions, conditional, ledger); } @@ -115,10 +257,10 @@ private static bool Prove(Entity left, Entity right, IReadOnlyList var graph = new EGraph(); var a = graph.AddEntity(left); var b = graph.AddEntity(right); - // The graph does not sort a commutative operand pair or flatten a nested sum -- the - // rules that do build their replacement in code, so no ceiling admits them -- and the - // canonical-form pass does both. It joins each side to its own canonical form, as one - // more conditional step: the pass declares SoundUnderAssumptions. + // The canonical-form pass sorts and also groups like terms, flattens differences and + // quotients and simplifies each side; OperandOrder only reorders. The pass joins each + // side to its own canonical form, as one more conditional step: it declares + // SoundUnderAssumptions. if (canonicalize) foreach (var (side, id) in new[] { (left, a), (right, b) }) { diff --git a/Sources/AngouriMath/Docs/Contributing/CanonicalForm.md b/Sources/AngouriMath/Docs/Contributing/CanonicalForm.md index 13ceb68df..0709830fa 100644 --- a/Sources/AngouriMath/Docs/Contributing/CanonicalForm.md +++ b/Sources/AngouriMath/Docs/Contributing/CanonicalForm.md @@ -265,6 +265,28 @@ worse than no form at all**, because its whole value was that structural equalit at all. Use the residual — `(a - b).Simplify()` against zero — and even that is a semi-decision, by §2. +To *ask* whether two expressions are equal, call `MathS.AreEqual(a, b, budget)` +([#1251](https://github.com/asc-community/AngouriMath/issues/1251)). It answers `Equal`, +`NotEqual` or `Unknown`, and each means one thing: + +- `Equal` only when both sides land in one class of an e-graph, which is a proof and not a + comparison of two canonical forms, so it does not need the rules to be confluent. The answer + carries the weakest soundness the proof rests on. Under the default, `Soundness.Sound`, only + rules that declare `Sound` fire, together with two steps of the oracle's own that reorder the + terms of a sum and the factors of a product and group nothing. Under `SoundUnderAssumptions` the + conditional rules and `Transformation.Canonicalization` fire as well, and the answer names the + ones that joined a class. +- `NotEqual` only with a witness: a point where the library's evaluation and an enclosure of every + subexpression say both sides are defined, and enclosures of the two values are disjoint. +- `Unknown` otherwise, which is not "unequal". The safe rules do not expand, so `(x + 1)^2` against + `x^2 + 2x + 1` is `Unknown`. + +The budget counts steps (a point tried, a match attempt, a node the graph grows by), so the same +question gets the same answer on any machine. A name is a number of the `domain` asked, so +`a * b` and `b * a` are `Equal`. A question with a matrix or a matrix operation anywhere in it has +no product reordered, because a name beside a transpose may stand for a matrix +([#2147](https://github.com/asc-community/AngouriMath/issues/2147)). + The one thing it *is* required to be is sound, which is [SimplificationContract.md](SimplificationContract.md). ## 7. How this is checked diff --git a/Sources/Tests/UnitTests/Common/PublicApi.txt b/Sources/Tests/UnitTests/Common/PublicApi.txt index acf885829..65965ac6b 100644 --- a/Sources/Tests/UnitTests/Common/PublicApi.txt +++ b/Sources/Tests/UnitTests/Common/PublicApi.txt @@ -277,6 +277,22 @@ AngouriMath.Core.Transformations.DerivationStep.Rewrites { } : System.Collection AngouriMath.Core.Transformations.DerivationStep.RuleSet { } : AngouriMath.Core.Transformations.RewriteRuleSet AngouriMath.Core.Transformations.DerivationStep.Soundness { } : System.Nullable AngouriMath.Core.Transformations.DerivationStep.ToString() : System.String +AngouriMath.Core.Transformations.EqualityAnswer.$() : AngouriMath.Core.Transformations.EqualityAnswer +AngouriMath.Core.Transformations.EqualityAnswer.Assumptions { } : System.Collections.Generic.IReadOnlyList +AngouriMath.Core.Transformations.EqualityAnswer.Budget { } : AngouriMath.Core.Budgets.BudgetOutcome +AngouriMath.Core.Transformations.EqualityAnswer.Equals(AngouriMath.Core.Transformations.EqualityAnswer) : System.Boolean +AngouriMath.Core.Transformations.EqualityAnswer.Equals(System.Object) : System.Boolean +AngouriMath.Core.Transformations.EqualityAnswer.GetHashCode() : System.Int32 +AngouriMath.Core.Transformations.EqualityAnswer.Justification { } : System.Nullable +AngouriMath.Core.Transformations.EqualityAnswer.ToString() : System.String +AngouriMath.Core.Transformations.EqualityAnswer.Verdict { } : AngouriMath.Core.Transformations.EqualityVerdict +AngouriMath.Core.Transformations.EqualityAnswer.Witness { } : System.Collections.Generic.IReadOnlyDictionary +AngouriMath.Core.Transformations.EqualityAnswer.op_Equality(AngouriMath.Core.Transformations.EqualityAnswer, AngouriMath.Core.Transformations.EqualityAnswer) : System.Boolean +AngouriMath.Core.Transformations.EqualityAnswer.op_Inequality(AngouriMath.Core.Transformations.EqualityAnswer, AngouriMath.Core.Transformations.EqualityAnswer) : System.Boolean +AngouriMath.Core.Transformations.EqualityVerdict.Equal : AngouriMath.Core.Transformations.EqualityVerdict +AngouriMath.Core.Transformations.EqualityVerdict.NotEqual : AngouriMath.Core.Transformations.EqualityVerdict +AngouriMath.Core.Transformations.EqualityVerdict.Unknown : AngouriMath.Core.Transformations.EqualityVerdict +AngouriMath.Core.Transformations.EqualityVerdict.value__ : System.Int32 AngouriMath.Core.Transformations.RewriteRecording.Derivation { } : System.Collections.Generic.IReadOnlyList AngouriMath.Core.Transformations.RewriteRecording.Dispose() : System.Void AngouriMath.Core.Transformations.RewriteRecording.PathFrom(AngouriMath.Entity, AngouriMath.Entity) : AngouriMath.Core.Transformations.DerivationPath @@ -3612,6 +3628,7 @@ AngouriMath.MathS.Arccotan(AngouriMath.Entity) : AngouriMath.Entity AngouriMath.MathS.Arcsec(AngouriMath.Entity) : AngouriMath.Entity AngouriMath.MathS.Arcsin(AngouriMath.Entity) : AngouriMath.Entity AngouriMath.MathS.Arctan(AngouriMath.Entity) : AngouriMath.Entity +AngouriMath.MathS.AreEqual(AngouriMath.Entity, AngouriMath.Entity, AngouriMath.Core.Budgets.WorkBudget, AngouriMath.Core.Transformations.Soundness, AngouriMath.Core.Domain) : AngouriMath.Core.Transformations.EqualityAnswer AngouriMath.MathS.Arg(AngouriMath.Entity) : AngouriMath.Entity AngouriMath.MathS.Argmax(AngouriMath.Entity, AngouriMath.Entity, AngouriMath.Entity) : AngouriMath.Entity AngouriMath.MathS.Argmin(AngouriMath.Entity, AngouriMath.Entity, AngouriMath.Entity) : AngouriMath.Entity @@ -3803,6 +3820,7 @@ class AngouriMath.Core.ReasonOfFailureWhileParsing+MissingOperator class AngouriMath.Core.ReasonOfFailureWhileParsing+Unknown class AngouriMath.Core.Serialization.EntityJsonConverter class AngouriMath.Core.Transformations.DerivationPath +class AngouriMath.Core.Transformations.EqualityAnswer class AngouriMath.Core.Transformations.RewriteRecording class AngouriMath.Core.Transformations.RewriteRule class AngouriMath.Core.Transformations.RewriteRuleSet @@ -3967,6 +3985,7 @@ class AngouriMath.ProofRecording class AngouriMath.ProofStep enum AngouriMath.Core.ApproachFrom enum AngouriMath.Core.Domain +enum AngouriMath.Core.Transformations.EqualityVerdict enum AngouriMath.Core.Transformations.RewriteRuleGrowth enum AngouriMath.Core.Transformations.Soundness enum AngouriMath.Core.Transformations.TransformationRelation diff --git a/Sources/Tests/UnitTests/Core/Transformations/AreEqualTest.cs b/Sources/Tests/UnitTests/Core/Transformations/AreEqualTest.cs index c905ef1d4..6ec6e9fc8 100644 --- a/Sources/Tests/UnitTests/Core/Transformations/AreEqualTest.cs +++ b/Sources/Tests/UnitTests/Core/Transformations/AreEqualTest.cs @@ -55,12 +55,9 @@ public void AnIdentityTheSoundRulesReachIsEqualUnconditionally(string left, stri /// An identity whose proof needs a step that declares /// is /// to a caller who asked for an unconditional proof, and - /// naming the steps to a caller who admits them. Commutativity is here because the graph - /// does not sort operands and the pass that does declares the weaker soundness. + /// naming the steps to a caller who admits them. /// [Theory] - [InlineData("x + y", "y + x", "canonicalization")] - [InlineData("x * y", "y * x", "canonicalization")] [InlineData("tan(x)", "sin(x) / cos(x)", "sine-over-cosine-is-the-tangent")] [InlineData("exp(x + y)", "exp(x) * exp(y)", "two-powers-of-one-base-multiply-by-adding-exponents")] [InlineData("x ^ 2 * x ^ 3", "x ^ 5", "two-powers-of-one-base-multiply-by-adding-exponents")] @@ -75,6 +72,122 @@ public void AConditionalProofIsEqualOnlyWhereItsConditionIsAdmitted(string left, Assert.Contains(admitted.Assumptions, name => name.StartsWith(step, StringComparison.Ordinal)); } + /// + /// Commutativity and associativity of a sum and of a product are unconditional over the + /// numbers, so reordering operands is a step: it groups + /// nothing, which is what keeps the canonical-form pass at the weaker soundness. + /// + [Theory] + [InlineData("x + y", "y + x")] + [InlineData("x * y", "y * x")] + [InlineData("a + b + c", "c + a + b")] + [InlineData("a + (b + c)", "(c + b) + a")] + [InlineData("a * b * c", "c * (b * a)")] + [InlineData("2 * x * y", "y * x * 2")] + [InlineData("x * y + z", "z + y * x")] + [InlineData("sin(x * y) + 1", "1 + sin(y * x)")] + [InlineData("(x + y) * (x - y)", "(x - y) * (y + x)")] + public void ReorderingASumOrAProductIsEqualUnconditionally(string left, string right) + { + foreach (var weakest in new[] { Soundness.Sound, Soundness.SoundUnderAssumptions }) + { + var answer = Ask(left, right, weakest); + Assert.Equal(EqualityVerdict.Equal, answer.Verdict); + Assert.Equal(Soundness.Sound, answer.Justification); + Assert.Empty(answer.Assumptions); + } + } + + /// + /// Matrices do not commute, so a product of two written matrices in the other order is + /// not proved: no witness either, since a matrix is not a value the sampling compares, + /// so the answer is . + /// + [Theory] + [InlineData("[[1, 2], [3, 4]] * [[0, 1], [1, 0]]", "[[0, 1], [1, 0]] * [[1, 2], [3, 4]]")] + [InlineData("x * [[1, 2], [3, 4]] * [[0, 1], [1, 0]]", "[[0, 1], [1, 0]] * [[1, 2], [3, 4]] * x")] + [InlineData("[[1, 2], [3, 4]] * [[0, 1], [1, 0]] + y", "y + [[0, 1], [1, 0]] * [[1, 2], [3, 4]]")] + public void AProductOfMatricesIsNotReordered(string left, string right) + { + foreach (var weakest in new[] { Soundness.Sound, Soundness.SoundUnderAssumptions }) + Assert.NotEqual(EqualityVerdict.Equal, Ask(left, right, weakest).Verdict); + } + + /// + /// A name carries no type, and the library reads one beside a transpose as possibly a + /// matrix (https://github.com/asc-community/AngouriMath/issues/2147). So a question with a + /// matrix operation anywhere in it reorders no product -- not even one the transpose is + /// not a factor of, since the same name may be multiplied there. + /// + [Theory] + [InlineData("transpose(A) * A", "A * transpose(A)")] + [InlineData("A * B + transpose(A)", "B * A + transpose(A)")] + [InlineData("A * B + det(A)", "B * A + det(A)")] + [InlineData("A * B + A[1, 1]", "B * A + A[1, 1]")] + public void AProductBesideAMatrixOperationIsNotReorderedSoundly(string left, string right) + { + Assert.NotEqual(EqualityVerdict.Equal, Ask(left, right).Verdict); + Assert.NotEqual(Soundness.Sound, Ask(left, right, Soundness.SoundUnderAssumptions).Justification); + } + + /// + /// The two reordering steps on their own: every order and grouping of one chain comes out + /// as the same tree, a difference or a quotient stays one operand, and a chain with an + /// operand that may not be a number is left as it is. The literal matrices are declined by + /// the step itself, not only by the e-graph, which cannot rebuild a matrix to show it. + /// + [Theory] + [InlineData("x + y + z", "z + (y + x)")] + [InlineData("(x + y) + z", "y + (z + x)")] + [InlineData("x * y * z", "z * (y * x)")] + [InlineData("(a - b) + c", "c + (a - b)")] + [InlineData("(a / b) * c", "c * (a / b)")] + public void TheReorderingStepsWriteEveryOrderOfAChainAlike(string left, string right) + => Assert.Equal(Reorder(left.ToEntity()), Reorder(right.ToEntity())); + + [Theory] + [InlineData("transpose(A) * A")] + [InlineData("A * transpose(A)")] + [InlineData("[[0, 1], [1, 0]] * [[1, 2], [3, 4]]")] + [InlineData("[[1, 2], [3, 4]] * [[0, 1], [1, 0]]")] + [InlineData("x * [[1, 2], [3, 4]]")] + [InlineData("[[1, 2], [3, 4]] * x")] + [InlineData("y + [[1, 2], [3, 4]]")] + [InlineData("[[1, 2], [3, 4]] + y")] + [InlineData("y * { 1, 2 }")] + [InlineData("{ 1, 2 } * y")] + [InlineData("y * (x > 0)")] + [InlineData("(x > 0) * y")] + public void TheReorderingStepsDeclineAnOperandThatMayNotCommute(string written) + { + // Each is written in both orders above, so the step would rewrite one of the two. + var expr = written.ToEntity(); + foreach (var rule in EqualityOracle.OperandOrder) + Assert.True(rule.TryApply(expr) is not { } rewritten || rewritten.Equals(expr), + $"{rule.Name} rewrote {expr}"); + } + + /// + /// A link of a chain read over a narrower codomain than its own keeps that reading: + /// rebuilding the chain would drop it, so the link is one operand. + /// + [Fact] + public void TheReorderingStepsKeepALinkReadOverANarrowerCodomain() + { + var narrowed = "y + x".ToEntity().WithCodomain(Domain.Real); + Assert.Equal(narrowed, Reorder(narrowed)); + var outer = (narrowed + "a".ToEntity()); + Assert.Equal(new Sumf("a", narrowed), Reorder(outer)); + } + + private static Entity Reorder(Entity expr) + { + foreach (var rule in EqualityOracle.OperandOrder) + if (rule.TryApply(expr) is { } rewritten) + expr = rewritten; + return expr; + } + /// /// Admitting conditional rules does not weaken a proof the sound rules make alone: the /// justification is the weakest the answer needs, not the weakest that was admitted. @@ -201,6 +314,8 @@ public void AHeuristicCannotJustifyAnEquality() [InlineData("sin(x) ^ 2 + cos(x) ^ 2", "1")] [InlineData("a * b + a * c", "a * (b + c)")] [InlineData("x + y", "y + x")] + [InlineData("a * b * c", "c * (b * a)")] + [InlineData("x * y + z", "z + y * x")] [InlineData("tan(x)", "sin(x) / cos(x)")] [InlineData("exp(x + y)", "exp(x) * exp(y)")] [InlineData("x ^ 2 * x ^ 3", "x ^ 5")] From 4ff08e9f40e7c174cd5dcf39a4ad888029ec4a43 Mon Sep 17 00:00:00 2001 From: Rafael Vuijk Date: Sun, 15 Nov 2026 00:52:21 +0000 Subject: [PATCH 3/3] Offer MathS.AreEqual as a catalogue entry and an MCP tool are_equal joins Core/Operations/Catalogue.cs: an operation offered by name is an entry there. The MCP server offers it as am_are_equal: left and right as strings, a step budget (default 20000), domain (complex or real) and the weakest soundness (sound or sound_under_assumptions). The answer states the verdict, the justification, the assumptions, the witness and what the budget did; unknown is "inconclusive" with equal null, never false. The description sets it apart from am_verify_equal, which may answer from sampling and believes a simplification. The terminal lists it in OneShot.notOffered: its one-shot commands are AngouriMathCLI's, and adding commands is #1019 item 16's question. Part of #1251. Co-Authored-By: Claude Opus 5.5 --- .../AngouriMath/Core/Operations/Catalogue.cs | 12 +- Sources/MCP/AngouriMath.Mcp/Tools.cs | 121 ++++++++++++++++++ Sources/MCP/README.md | 6 + .../AngouriMath.Terminal.Lib/OneShot.fs | 2 +- Sources/Tests/McpUnitTests/ServerTest.cs | 2 +- Sources/Tests/McpUnitTests/ToolsTest.cs | 73 +++++++++++ .../Core/Operations/CatalogueTest.cs | 5 + 7 files changed, 218 insertions(+), 3 deletions(-) diff --git a/Sources/AngouriMath/Core/Operations/Catalogue.cs b/Sources/AngouriMath/Core/Operations/Catalogue.cs index 4390c8465..19d128a4e 100644 --- a/Sources/AngouriMath/Core/Operations/Catalogue.cs +++ b/Sources/AngouriMath/Core/Operations/Catalogue.cs @@ -8,6 +8,7 @@ using System; using System.Collections.Generic; using System.Linq; +using AngouriMath.Core.Budgets; using AngouriMath.Core.Transformations; using static AngouriMath.Entity; using static AngouriMath.Entity.Number; @@ -157,6 +158,15 @@ internal static class Catalogue : MathS.Series.Taylor(e, degree + 1, (variable, around)), TheVariable, new Parameter("degree", "The highest power kept."), new Parameter("around", "The point, or none for zero.")); + /// . + public static Query> AreEqual { get; } = new( + "are_equal", "Decides whether two expressions are equal: proved by rewrite rules, refuted at a point where both are defined, or neither within the budget.", + static (left, right, budget, weakest, domain) => MathS.AreEqual(left, right, budget, weakest, domain), + new Parameter("other", "The expression on the right."), + new Parameter("budget", "What the question may spend, in steps for an answer that does not depend on the machine."), + new Parameter("weakest", "The weakest soundness a proof may rest on: sound, or sound under assumptions."), + new Parameter("domain", "Where the variables range: the complex or the real numbers.")); + // ---------------------------------------------------------------- queries on a number /// . @@ -244,7 +254,7 @@ internal static class Catalogue public static IReadOnlyList All { get; } = [ Simplify, Normalize, Expand, Factorize, Differentiate, Integrate, Limit, Substitute, - Solve, SolveSystem, Evaluate, EvaluateNumerically, Variables, Alternatives, Latex, Sympy, TruthTable, SatisfyingAssignments, Series, + Solve, SolveSystem, Evaluate, EvaluateNumerically, Variables, Alternatives, Latex, Sympy, TruthTable, SatisfyingAssignments, Series, AreEqual, ToBase, FromBase, Determinant, Inverse, Transpose, Rank, ReducedRowEchelonForm, Trace, TensorProduct, PrimeFactorization, Totient, GreatestCommonDivisor, DivisorCount, IsPrime, diff --git a/Sources/MCP/AngouriMath.Mcp/Tools.cs b/Sources/MCP/AngouriMath.Mcp/Tools.cs index a6e0fd9f3..eb4d74399 100644 --- a/Sources/MCP/AngouriMath.Mcp/Tools.cs +++ b/Sources/MCP/AngouriMath.Mcp/Tools.cs @@ -104,6 +104,7 @@ private static JsonObject Schema(JsonObject props, params string[] required) ["am_number_theory"] = [Catalogue.PrimeFactorization, Catalogue.Totient, Catalogue.GreatestCommonDivisor, Catalogue.DivisorCount, Catalogue.IsPrime], ["am_to_sympy"] = [Catalogue.Sympy], + ["am_are_equal"] = [Catalogue.AreEqual], }; /// @@ -272,6 +273,43 @@ private static JsonObject[] All() => ["right"] = Str("Second expression."), }, "left", "right")), + Tool("am_are_equal", + "Ask whether two expressions are equal, and get one of three answers, each a claim " + + "you can rely on: 'equal' only with a proof (both sides rewritten into one class of " + + "an e-graph, by rules that state their soundness), 'not_equal' only with a witness " + + "(a point where both sides are defined and provably differ), and 'unknown' " + + "otherwise — which is NOT 'unequal'. Unlike am_verify_equal it never decides by " + + "sampling alone and never believes a simplification: use it when the answer has to " + + "be a proof or a counter-example. Bounded by a step budget, so the same question " + + "gets the same answer on any machine.", + Schema(new JsonObject + { + ["left"] = Str("First expression."), + ["right"] = Str("Second expression."), + ["steps"] = new JsonObject + { + ["type"] = "integer", + ["description"] = "Work budget in steps (a point tried, a rule's match attempt, a node " + + "the graph grows by), 1-1000000. Default 20000. An 'unknown' that says the " + + "budget stopped it may become an answer with more.", + }, + ["domain"] = new JsonObject + { + ["type"] = "string", + ["enum"] = new JsonArray("complex", "real"), + ["description"] = "Where the variables range, and so where a witness may be. " + + "Default 'complex'. sqrt(x^2) and abs(x) are not_equal over complex, unknown over real.", + }, + ["weakest"] = new JsonObject + { + ["type"] = "string", + ["enum"] = new JsonArray("sound", "sound_under_assumptions"), + ["description"] = "The weakest soundness a proof may rest on. Default 'sound': only " + + "rules with no side condition. 'sound_under_assumptions' admits conditional " + + "rules too and names them in 'assumptions'.", + }, + }, "left", "right")), + Tool("am_truth_table", "Build a truth table for a boolean expression, and list the assignments that " + "satisfy it. Useful for reasoning about branch conditions and predicates. " + @@ -617,6 +655,7 @@ public static JsonObject Call(string name, JsonObject args, bool preliminary) "am_number_theory" => NumberTheory(args), "am_classify" => ClassifyFormula(args), "am_to_sympy" => ToSympy(args), + "am_are_equal" => AreEqual(args), _ => Fail($"unknown tool '{name}'"), }; @@ -1222,6 +1261,88 @@ private static JsonObject VerifyEqual(JsonObject args) }); } + private static JsonObject AreEqual(JsonObject args) + { + if (!TryParse(S(args, "left"), "left", false, out var left, out var lw, out var le)) + return le!; + if (!TryParse(S(args, "right"), "right", false, out var right, out var rw, out var re)) + return re!; + + var steps = args.TryGetPropertyValue("steps", out var st) && st is not null + ? st.GetValue() : 20_000; + if (steps is < 1 or > 1_000_000) return Fail("'steps' must be between 1 and 1000000"); + Domain domain; + switch (S(args, "domain") ?? "complex") + { + case "complex": domain = Domain.Complex; break; + case "real": domain = Domain.Real; break; + default: return Fail("'domain' must be 'complex' or 'real'"); + } + AngouriMath.Core.Transformations.Soundness weakest; + switch (S(args, "weakest") ?? "sound") + { + case "sound": weakest = AngouriMath.Core.Transformations.Soundness.Sound; break; + case "sound_under_assumptions": weakest = AngouriMath.Core.Transformations.Soundness.SoundUnderAssumptions; break; + default: return Fail("'weakest' must be 'sound' or 'sound_under_assumptions'"); + } + + var budget = new AngouriMath.Core.Budgets.WorkBudget { Steps = steps }; + return FromOutcome(Guard.Run(() => Catalogue.AreEqual.Ask(left, right, budget, weakest, domain)), answer => + { + var verdict = answer.Verdict switch + { + AngouriMath.Core.Transformations.EqualityVerdict.Equal => "equal", + AngouriMath.Core.Transformations.EqualityVerdict.NotEqual => "not_equal", + _ => "unknown", + }; + var assumptions = new JsonArray(); + foreach (var step in answer.Assumptions) assumptions.Add(step); + JsonObject? witness = null; + if (answer.Witness is { } point) + { + witness = new JsonObject(); + foreach (var (variable, value) in point.OrderBy(p => p.Key.Name, StringComparer.Ordinal)) + witness[variable.Name] = value.Stringize(); + } + var response = new JsonObject + { + // Unknown is "inconclusive", never false: not proved is not refuted. + ["status"] = verdict == "unknown" ? "inconclusive" : "solved", + ["verdict"] = verdict, + ["equal"] = verdict switch { "equal" => true, "not_equal" => false, _ => null }, + ["justification"] = answer.Justification switch + { + AngouriMath.Core.Transformations.Soundness.Sound => "sound", + AngouriMath.Core.Transformations.Soundness.SoundUnderAssumptions => "sound_under_assumptions", + _ => null, + }, + ["assumptions"] = assumptions, + ["witness"] = witness, + ["budget"] = new JsonObject + { + ["steps"] = answer.Budget.Steps, + ["completed"] = answer.Budget.Completed, + ["stopped_by"] = answer.Budget.Reason, + }, + ["left_parsed"] = left.Stringize(), + ["right_parsed"] = right.Stringize(), + ["note"] = verdict switch + { + "equal" when answer.Assumptions.Count == 0 => "Proved equal, with no side condition.", + "equal" => "Proved equal by steps that hold only under conditions; 'assumptions' names them. " + + "Ask again with weakest='sound' for an unconditional answer.", + "not_equal" => "The two sides differ at 'witness', where both are defined.", + _ => answer.Budget.Completed + ? "Neither proved nor refuted: the rules ran out of moves. Not proof of inequality." + : "Neither proved nor refuted before the budget ran out. Not proof of inequality; " + + "more 'steps' may settle it.", + }, + ["warnings"] = Warn([.. lw, .. rw]), + }; + return response; + }); + } + private static JsonObject TruthTable(JsonObject args) { if (!TryParse(S(args, "expression"), "expression", false, diff --git a/Sources/MCP/README.md b/Sources/MCP/README.md index df9c1ca9a..c8c510c2a 100644 --- a/Sources/MCP/README.md +++ b/Sources/MCP/README.md @@ -59,6 +59,7 @@ echo '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}' | amcli mcp | `am_limit` | one-sided with `side`; tells "no limit" from failure | | `am_evaluate` | the exact form and a decimal, after optional substitutions | | `am_verify_equal` | did your own algebra change the meaning? Names the difference | +| `am_are_equal` | `equal` only with a proof, `not_equal` only with a witness point, else `unknown`; never decided by sampling alone. Bounded in steps | | `am_check_steps` | checks a chain of working and names the step that broke | | `am_truth_table` | the table and the satisfying assignments | | `am_solve_system` | takes `x + y = 3` as well as `x + y - 3` | @@ -137,6 +138,11 @@ a deep recursion takes the server down. - `am_verify_equal` decides on positive real points, then checks the negatives separately: for `sqrt(x^2)` against `x` it answers `equal: true` **with a note** that the two agree only on the positives. The note is part of the answer. +- `am_are_equal` answers `unknown` often and honestly: its rules do not expand, so `(x + 1)^2` + against `x^2 + 2x + 1` is `unknown`, and it reads a name as a number, so `a*b` and `b*a` are + `equal` unless a matrix or a matrix operation is written somewhere in the question. Its + `not_equal` comes with a point, so the agent can check it. `am_verify_equal` gives a yes or no + more often, and its yes may rest on sampling. - `am_solve`'s `solutions[]` is tidied root by root and its raw `result` is not, so the two can read differently. Prefer `solutions[]`. - A nonlinear system can come back with no solution when one exists. diff --git a/Sources/Terminal/AngouriMath.Terminal.Lib/OneShot.fs b/Sources/Terminal/AngouriMath.Terminal.Lib/OneShot.fs index a985e7c11..620cbd9e0 100644 --- a/Sources/Terminal/AngouriMath.Terminal.Lib/OneShot.fs +++ b/Sources/Terminal/AngouriMath.Terminal.Lib/OneShot.fs @@ -70,7 +70,7 @@ let notOffered = set [ "expand"; "factorize"; "integrate"; "limit"; "solve_system"; "evaluate_numerically"; "variables" "alternatives"; "sympy"; "truth_table"; "satisfying_assignments"; "series"; "to_base"; "from_base" "determinant"; "inverse"; "transpose"; "rank"; "reduced_row_echelon_form"; "trace"; "tensor_product" - "prime_factorization"; "totient"; "greatest_common_divisor"; "divisor_count"; "is_prime" ] + "prime_factorization"; "totient"; "greatest_common_divisor"; "divisor_count"; "is_prime"; "are_equal" ] /// The arguments still to read, falling back to a line of stdin where one is missing or is _. type private Arguments(given: string list, input: TextReader) = diff --git a/Sources/Tests/McpUnitTests/ServerTest.cs b/Sources/Tests/McpUnitTests/ServerTest.cs index e4aacc56c..f0aa87041 100644 --- a/Sources/Tests/McpUnitTests/ServerTest.cs +++ b/Sources/Tests/McpUnitTests/ServerTest.cs @@ -70,7 +70,7 @@ public void EveryToolIsReadOnlyAndClosedWorld() // An MCP client can approve these without asking, which is what gets a maths tool // used at all. var tools = Mcp.Request("tools/list", preliminary: true)["tools"]!.AsArray(); - Assert.Equal(23, tools.Count); + Assert.Equal(24, tools.Count); foreach (var tool in tools) { var name = tool!["name"]!.GetValue(); diff --git a/Sources/Tests/McpUnitTests/ToolsTest.cs b/Sources/Tests/McpUnitTests/ToolsTest.cs index 7c57762ee..508217fc8 100644 --- a/Sources/Tests/McpUnitTests/ToolsTest.cs +++ b/Sources/Tests/McpUnitTests/ToolsTest.cs @@ -134,6 +134,79 @@ public void VerifyEqualNamesTheDifference(string left, string right, bool equal, Assert.Equal(difference, answer.Field("difference")); } + [Fact] + public void AreEqualProvesAReorderingUnconditionally() + { + var answer = Mcp.Call("am_are_equal", """{"left":"a*b + c","right":"c + b*a"}"""); + Assert.Equal("solved", answer.Field("status")); + Assert.Equal("equal", answer.Field("verdict")); + Assert.True(answer["equal"]!.GetValue()); + Assert.Equal("sound", answer.Field("justification")); + Assert.Empty(answer["assumptions"]!.AsArray()); + Assert.True(answer["budget"]!["completed"]!.GetValue()); + } + + /// A refutation comes with the point, and the point checks. + [Fact] + public void AreEqualRefutesWithAWitness() + { + var answer = Mcp.Call("am_are_equal", """{"left":"ln(x*y)","right":"ln(x) + ln(y)"}"""); + Assert.Equal("not_equal", answer.Field("verdict")); + Assert.False(answer["equal"]!.GetValue()); + var witness = answer["witness"]!.AsObject(); + Entity left = "ln(x*y)", right = "ln(x) + ln(y)"; + foreach (var (name, value) in witness) + { + Entity at = value!.GetValue(); + left = left.Substitute(MathS.Var(name), at); + right = right.Substitute(MathS.Var(name), at); + } + Assert.True(System.Numerics.Complex.Abs(left.EvalNumerical().ToNumerics() - right.EvalNumerical().ToNumerics()) > 1e-6); + } + + /// + /// Unknown is inconclusive, never false; and a conditional proof says so, and names its step. + /// + [Fact] + public void AreEqualSaysUnknownAndConditionalPlainly() + { + var unknown = Mcp.Call("am_are_equal", """{"left":"(x+1)^2","right":"x^2 + 2*x + 1"}"""); + Assert.Equal("inconclusive", unknown.Field("status")); + Assert.Equal("unknown", unknown.Field("verdict")); + Assert.Null(unknown["equal"]); + + var sound = Mcp.Call("am_are_equal", """{"left":"tan(x)","right":"sin(x)/cos(x)"}"""); + Assert.Equal("unknown", sound.Field("verdict")); + var conditional = Mcp.Call("am_are_equal", """{"left":"tan(x)","right":"sin(x)/cos(x)","weakest":"sound_under_assumptions"}"""); + Assert.Equal("equal", conditional.Field("verdict")); + Assert.Equal("sound_under_assumptions", conditional.Field("justification")); + Assert.NotEmpty(conditional["assumptions"]!.AsArray()); + } + + [Fact] + public void AreEqualLooksForAWitnessOnlyWhereTheVariablesRange() + { + Assert.Equal("not_equal", Mcp.Call("am_are_equal", """{"left":"sqrt(x^2)","right":"abs(x)"}""").Field("verdict")); + Assert.Equal("unknown", Mcp.Call("am_are_equal", """{"left":"sqrt(x^2)","right":"abs(x)","domain":"real"}""").Field("verdict")); + } + + [Theory] + [InlineData("""{"left":"x","right":"x","steps":0}""")] + [InlineData("""{"left":"x","right":"x","domain":"rational"}""")] + [InlineData("""{"left":"x","right":"x","weakest":"heuristic"}""")] + public void AreEqualRefusesAnArgumentOutOfRange(string args) + => Assert.Equal("failed", Mcp.Call("am_are_equal", args).Field("status")); + + /// A budget too small to answer says the budget stopped it. + [Fact] + public void AreEqualUnderASmallBudgetSaysWhy() + { + var answer = Mcp.Call("am_are_equal", """{"left":"(x+y)*(x-y)","right":"x^2 - y^2","steps":3}"""); + Assert.Equal("unknown", answer.Field("verdict")); + Assert.False(answer["budget"]!["completed"]!.GetValue()); + Assert.NotNull(answer["budget"]!["stopped_by"]); + } + [Fact] public void TruthTableListsTheSatisfyingAssignments() { diff --git a/Sources/Tests/UnitTests/Core/Operations/CatalogueTest.cs b/Sources/Tests/UnitTests/Core/Operations/CatalogueTest.cs index 996d6094f..292cbe107 100644 --- a/Sources/Tests/UnitTests/Core/Operations/CatalogueTest.cs +++ b/Sources/Tests/UnitTests/Core/Operations/CatalogueTest.cs @@ -223,6 +223,11 @@ public void EachEntryAnswersAsTheMethodItNames() Assert.Equal(MathS.Series.Maclaurin("e^x", 4, x), Catalogue.Series.Ask("e^x", x, 3, null)); Assert.Equal(MathS.Series.Taylor("e^x", 4, (x, 1)), Catalogue.Series.Ask("e^x", x, 3, 1)); Assert.NotEqual(Catalogue.Series.Ask("e^x", x, 3, null), Catalogue.Series.Ask("e^x", x, 3, 1)); + var steps = new AngouriMath.Core.Budgets.WorkBudget { Steps = 20_000 }; + Assert.Equal(MathS.AreEqual("x + y", "y + x", steps).Verdict, Catalogue.AreEqual.Ask("x + y", "y + x", steps, Soundness.Sound, Domain.Complex).Verdict); + Assert.Equal(EqualityVerdict.Equal, Catalogue.AreEqual.Ask("x + y", "y + x", steps, Soundness.Sound, Domain.Complex).Verdict); + Assert.Equal(EqualityVerdict.NotEqual, Catalogue.AreEqual.Ask("ln(e^x)", "x", steps, Soundness.Sound, Domain.Complex).Verdict); + Assert.Equal(EqualityVerdict.Unknown, Catalogue.AreEqual.Ask("ln(e^x)", "x", steps, Soundness.Sound, Domain.Real).Verdict); Assert.Equal(MathS.ToBaseN(10.5m, 2), Catalogue.ToBase.Ask(10.5m, 2)); Assert.Equal(MathS.FromBaseN("1010.1", 2), Catalogue.FromBase.Ask("1010.1", 2));