diff --git a/Sources/AngouriMath/Functions/Algebra/Polynomials/PolynomialFactoring.cs b/Sources/AngouriMath/Functions/Algebra/Polynomials/PolynomialFactoring.cs index 54f2613fd..bd4cb905b 100644 --- a/Sources/AngouriMath/Functions/Algebra/Polynomials/PolynomialFactoring.cs +++ b/Sources/AngouriMath/Functions/Algebra/Polynomials/PolynomialFactoring.cs @@ -323,8 +323,10 @@ internal static bool TryGetRationalCoefficients( // https://github.com/asc-community/AngouriMath/issues/746 if (!MayBeAPolynomialWithRationalCoefficients(expr, x)) return false; + // Through the simplification's expansions: it asks this of every candidate in every + // variable, and of the same candidates again in its nested runs. var monomials = PolynomialSolver.GatherMonomialInformation( - Sumf.LinearChildren(expr.Expand()), x); + Sumf.LinearChildren(Simplificator.Expanded(expr)), x); if (monomials is null || monomials.Count < leastTerms) return false; diff --git a/Sources/AngouriMath/Functions/Simplification/Simplificator.cs b/Sources/AngouriMath/Functions/Simplification/Simplificator.cs index 7fe11a45a..00809b742 100644 --- a/Sources/AngouriMath/Functions/Simplification/Simplificator.cs +++ b/Sources/AngouriMath/Functions/Simplification/Simplificator.cs @@ -41,6 +41,119 @@ internal static Entity PickSimplest(Entity one, Entity another) /// See more details in internal static Entity Simplify(Entity expr, int level) + { + simplifying++; + try + { + // A nested run is looked up in what the runs before it answered; the outermost + // one has no runs before it. See simplifications. + if (simplifying == 1 || RewriteRecording.Current is not null || !expr.Nodes.All(IsElementary)) + return SimplifyAtDepth(expr, level); + var kept = simplifications ??= new(); + if (kept.TryGetValue((expr, level), out var known) && Convenience.SettingsState.StillHolds(known.Under)) + return known.Simplified; + var under = Convenience.SettingsState.Snapshot(); + var simplified = SimplifyAtDepth(expr, level); + if (kept.Count >= MostKept) + kept.Clear(); + kept[(expr, level)] = (simplified, under); + return simplified; + } + finally + { + if (--simplifying == 0) + (expansions, simplifications) = (null, null); + } + } + + /// + /// How many calls this thread is inside: what the + /// nested runs kept is dropped when the outermost one returns. + /// + [ThreadStatic] private static int simplifying; + + /// + /// What the nested runs of the outermost on this + /// thread answered, by the tree and the level asked, each with the settings it was + /// answered under. + /// + /// + /// A sum of two fractions simplifies its numerator and the product of its denominators, + /// and a candidate's expansion and factorisation are simplified again, each a nested run + /// of its own; the passes of every run meet the same sums, so the same trees are asked + /// over and over. Under u = sqrt((a x + 1)/(a x - 1)) Rubi's 7.4.2 + /// e^(arcoth(a x)) (c - c/(a^2 x^2))^4 leaves a rational function whose + /// simplification ran 1232 nested ones, of 214 trees. Kept on the terms + /// states: elementary trees only, used only under the settings + /// they were answered under, and nothing where a derivation is being recorded. + /// https://github.com/asc-community/AngouriMath/issues/746 + /// + [ThreadStatic] private static Dictionary<(Entity, int), (Entity Simplified, object?[] Under)>? simplifications; + + /// + /// The expansions the polynomial passes made inside the outermost + /// on this thread, by the tree expanded, each with the + /// settings it was made under. + /// + /// + /// + /// expands each candidate and reads the expansion as a polynomial + /// in every variable in turn, and then factors it in every variable, which expands it + /// again; and nested simplifications meet the same candidate again, since a sum of + /// fractions simplifies the product of its denominators afresh at each pass that meets + /// it. t^4/((b t^2 + a + a t^2)^2 (1 + t^2)), the tangent's integrand for Rubi's + /// 4.1.7 sin(c + d x)^4/(a + b sin(c + d x)^2)^2, expanded one product of 342 + /// terms 72 times, 24 trees of it three variables each, at 145 MB a time: 11 GB of + /// the 12 GB its simplification cost. Under u = sqrt((a x + 1)/(a x - 1)) Rubi's + /// 7.4.2 e^(arcoth(a x)) (c - c/(a^2 x^2))^4 asked to factor 200 polynomials in + /// 1 - u^2 2145 times, most of them past the degree the factoring takes and + /// expanded to be told so: 5.4 GB. + /// + /// + /// The expansion of a tree of numbers, variables, arithmetic and the elementary functions + /// is a function of the tree and the settings, so one kept is the one the pass would make + /// again: a tree is looked up by its value, and an expansion is used only while every + /// setting reads as it did when it was made. Nothing else is kept -- a piecewise, a + /// calculus operator or a statement simplifies through scopes of its own, an integral by + /// integrating -- and nothing at all where a derivation is being recorded, whose steps the + /// expansion writes down each time it runs. + /// https://github.com/asc-community/AngouriMath/issues/746 + /// + /// + [ThreadStatic] private static Dictionary? expansions; + + /// + /// The most entries or holds before + /// it is emptied. + /// + private const int MostKept = 1024; + + /// + /// expanded, as expands it, from + /// where it is there: inside a simplification the polynomial + /// readers it asks expand through this. + /// + internal static Entity Expanded(Entity expr) + { + if (simplifying == 0 || RewriteRecording.Current is not null || !expr.Nodes.All(IsElementary)) + return expr.Expand(); + var kept = expansions ??= new(); + if (kept.TryGetValue(expr, out var known) && Convenience.SettingsState.StillHolds(known.Under)) + return known.Expanded; + var under = Convenience.SettingsState.Snapshot(); + var expanded = expr.Expand(); + if (kept.Count >= MostKept) + kept.Clear(); + kept[expr] = (expanded, under); + return expanded; + } + + /// A node whose simplification reads nothing but its children and the settings. + private static bool IsElementary(Entity node) + => node is Number or Variable or Sumf or Minusf or Mulf or Divf or Powf or Logf + or TrigonometricFunction or Absf or Signumf; + + private static Entity SimplifyAtDepth(Entity expr, int level) { var recording = RewriteRecording.Current; var simplified = Simplified(recording, Alternate(expr, level).First()); @@ -421,10 +534,15 @@ void __IterAddHistory(Entity expr) AddHistory(res = Simplified(recording, res.Rewrite(RewriteRules.PhiFunction))); Entity? possiblePoly = null; + // Expanded once for every variable rather than once a variable: the expansion + // does not depend on which one it is then read in. + Entity? expanded = null; foreach (var var in res.Vars) { var polyMark = recording?.Mark() ?? 0; - if (TryPolynomial(res, var, out var resPoly) + if ((recording is null + ? TryPolynomialOfExpanded(expanded ??= Expanded(res), var, out var resPoly) + : TryPolynomial(res, var, out resPoly)) && (possiblePoly is null || resPoly.Complexity < possiblePoly.Complexity)) AddHistory(possiblePoly = Noted(recording, res, resPoly, "AsPolynomial", polyMark)); } @@ -461,7 +579,7 @@ not solve this issue completely and yet too slow to be accepted. if (level > 0) // if level < 0 we don't check whether expanded version is better { var expandMark = recording?.Mark() ?? 0; - AddHistory(Noted(recording, res, res.Expand(), nameof(Entity.Expand), expandMark).Simplify(-CandidateLevel(level))); + AddHistory(Noted(recording, res, Expanded(res), nameof(Entity.Expand), expandMark).Simplify(-CandidateLevel(level))); var factorizeMark = recording?.Mark() ?? 0; // The **rule-based** factorisation, not `Entity.Factorize` -- which now also asks // the polynomial layer, and whose answers must not become candidates here. The @@ -494,7 +612,7 @@ not solve this issue completely and yet too slow to be accepted. // Expanded, and for the same reason res is expanded above: the // cancellation only shows up once the products are multiplied out. var openedMark = recording?.Mark() ?? 0; - AddHistory(Noted(recording, openedAngles, openedAngles.Expand(), nameof(Entity.Expand), openedMark).Simplify(-CandidateLevel(level))); + AddHistory(Noted(recording, openedAngles, Expanded(openedAngles), nameof(Entity.Expand), openedMark).Simplify(-CandidateLevel(level))); } } @@ -508,9 +626,15 @@ not solve this issue completely and yet too slow to be accepted. internal static bool TryPolynomial(Entity expr, Variable variable, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out Entity? dst) + => TryPolynomialOfExpanded(expr.Expand(), variable, out dst); + + /// of an expression already expanded. + private static bool TryPolynomialOfExpanded(Entity expanded, Variable variable, + [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] + out Entity? dst) { dst = null; - var children = Sumf.LinearChildren(expr.Expand()); + var children = Sumf.LinearChildren(expanded); var monomialsByPower = Algebra.AnalyticalSolving.PolynomialSolver.GatherMonomialInformation (children, variable); if (monomialsByPower == null) diff --git a/Sources/Tests/DotnetBenchmark/performance-baseline.json b/Sources/Tests/DotnetBenchmark/performance-baseline.json index 84941eb00..7f8d240b8 100644 --- a/Sources/Tests/DotnetBenchmark/performance-baseline.json +++ b/Sources/Tests/DotnetBenchmark/performance-baseline.json @@ -1,94 +1,94 @@ { "comment": "Allocated bytes and mean nanoseconds per operation for the popular use cases of https://github.com/asc-community/AngouriMath/issues/746. Checked by PerformanceGate.cs; see Sources/AngouriMath/Docs/WhatsNew/version_performance_control.md for when updating it is legitimate.", "benchmark": "CommonFunctionsInterVersion", - "commit": "7c0dce12e6e60cb8ce33a7aae661805a9e7cab99", - "measuredOn": "2026-09-28", - "runtime": ".NET 10.0.10", - "machine": "Ubuntu 26.04 LTS, X64, 8 logical cores", + "commit": "5edd6a1f8a0e9032b314b2ceeae8e80d648e6358", + "measuredOn": "2026-10-21", + "runtime": ".NET 10.0.13", + "machine": "Ubuntu 24.04.5 LTS, X64, 4 logical cores", "cases": { "CompileEasy": { - "allocatedBytes": 11031, - "meanNanoseconds": 187148.49052734376 + "allocatedBytes": 11003, + "meanNanoseconds": 330806.3571777344 }, "CompileHard": { - "allocatedBytes": 20434, - "meanNanoseconds": 312400.38727678574 + "allocatedBytes": 20398, + "meanNanoseconds": 577621.3629557291 }, "Derivate": { - "allocatedBytes": 55783, - "meanNanoseconds": 14270.340443929037 + "allocatedBytes": 56245, + "meanNanoseconds": 27684.57133131761 }, "EvalEasy": { "allocatedBytes": 0, - "meanNanoseconds": 2.082944576193889 + "meanNanoseconds": 4.0538319910948095 }, "EvalPolynomialFresh": { "allocatedBytes": 12536, - "meanNanoseconds": 4116.869101206462 + "meanNanoseconds": 8084.578495279948 }, "EvalPolynomialFresh15Digits": { "allocatedBytes": 12064, - "meanNanoseconds": 4281.885651179722 + "meanNanoseconds": 8616.347739083427 }, "EvalTranscendentalFresh": { "allocatedBytes": 34760, - "meanNanoseconds": 16291.656792776925 + "meanNanoseconds": 30158.402158610024 }, "EvalTrig": { "allocatedBytes": 69944, - "meanNanoseconds": 32223.94764811198 + "meanNanoseconds": 58949.92800467355 }, "EvalTrigPrecise": { - "allocatedBytes": 336552, - "meanNanoseconds": 410607.1845703125 + "allocatedBytes": 336553, + "meanNanoseconds": 721994.4565104167 }, "ParseEasy": { - "allocatedBytes": 18373, - "meanNanoseconds": 5579.264629109701 + "allocatedBytes": 18412, + "meanNanoseconds": 11023.764210292271 }, "ParseHard": { - "allocatedBytes": 59871, - "meanNanoseconds": 25569.49151611328 + "allocatedBytes": 60023, + "meanNanoseconds": 55330.677834647046 }, "RunEasy": { "allocatedBytes": 0, - "meanNanoseconds": 20.103014286075318 + "meanNanoseconds": 49.59855388317789 }, "RunHard": { "allocatedBytes": 0, - "meanNanoseconds": 293.32832632746016 + "meanNanoseconds": 571.6311563650767 }, "RunMedium": { "allocatedBytes": 0, - "meanNanoseconds": 164.38394159930093 + "meanNanoseconds": 322.09172677993774 }, "SimplifyEasy": { - "allocatedBytes": 79010, - "meanNanoseconds": 43888.25782877604 + "allocatedBytes": 79681, + "meanNanoseconds": 87608.15931803385 }, "SimplifyHard": { - "allocatedBytes": 175442312, - "meanNanoseconds": 110382788.55 + "allocatedBytes": 157895384, + "meanNanoseconds": 166394909.7647059 }, "SolveEasy": { - "allocatedBytes": 453621, - "meanNanoseconds": 205587.90686035156 + "allocatedBytes": 453424, + "meanNanoseconds": 436456.99151141825 }, "SolveEasyMedium": { - "allocatedBytes": 66576, - "meanNanoseconds": 18447.484899902345 + "allocatedBytes": 66661, + "meanNanoseconds": 37503.79045003255 }, "SolveHard": { - "allocatedBytes": 10148544, - "meanNanoseconds": 78453427.95959596 + "allocatedBytes": 9996973, + "meanNanoseconds": 110732013.08888888 }, "SolveMedium": { - "allocatedBytes": 457918, - "meanNanoseconds": 272234.59720284597 + "allocatedBytes": 458456, + "meanNanoseconds": 534248.4147385817 }, "SolveMediumHard": { - "allocatedBytes": 1407676, - "meanNanoseconds": 8650714.277083334 + "allocatedBytes": 1410754, + "meanNanoseconds": 16481988.640625 } }, "ungated": { diff --git a/Sources/Tests/UnitTests/Calculus/ExpansionsKeptAcrossASimplificationIntegralTest.cs b/Sources/Tests/UnitTests/Calculus/ExpansionsKeptAcrossASimplificationIntegralTest.cs new file mode 100644 index 000000000..9b537687a --- /dev/null +++ b/Sources/Tests/UnitTests/Calculus/ExpansionsKeptAcrossASimplificationIntegralTest.cs @@ -0,0 +1,77 @@ +// +// 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 AngouriMath.Extensions; +using Xunit; + +namespace AngouriMath.Tests.Calculus +{ + /// + /// The rational functions a substitution leaves are simplified, and a simplification's + /// nested runs expanded, factored and simplified the same trees over and over: the tangent's + /// integrand for Rubi's 4.1.7 sin(c + d x)^4/(a + b sin(c + d x)^2)^2 cost 12 GB, 11 GB + /// of it one product of 342 terms expanded 72 times. Each is now done once a simplification. + /// The answers are the ones made afresh gave; the symbols are this test's own, so that no + /// answer the integrator remembers from another test is what is measured. + /// #746 + /// + [Trait("Area", "Calculus")] + public sealed class ExpansionsKeptAcrossASimplificationIntegralTest + { + /// + /// Made afresh, the four cost 12.1, 8.8, 7.8 and 21.6 GB; kept, 0.4, 0.5, 0.8 and 2.6. The + /// last is mostly polynomials in 1 - u^2 factored past the degree the factoring + /// takes, and the simplifications of the sums they came from. + /// + [Theory] + [InlineData("sin(kc + kd*x)^4/(ka + kb*sin(kc + kd*x)^2)^2", 3_000_000_000L, -1.2, -0.7, 0.3, 0.8, 1.3, 2.1)] + [InlineData("csc(kc + kd*x)^4/(ka + kb*sin(kc + kd*x)^2)^2", 3_000_000_000L, -1.2, -0.7, 0.3, 0.8, 1.3, 2.1)] + [InlineData("e^acoth(ka*x)/(kc - kc/(ka*x))^4", 3_000_000_000L, 0.9, 1.3, 1.7, 2.2, 2.9, 3.6)] + [InlineData("e^acoth(ka*x)*(kc - kc/(ka^2*x^2))^4", 8_000_000_000L, 0.9, 1.3, 1.7, 2.2, 2.9, 3.6)] + public void AnsweredAsBeforeForAFractionOfTheAllocation(string integrand, long bytes, double p1, double p2, double p3, double p4, double p5, double p6) + { + var before = GC.GetAllocatedBytesForCurrentThread(); + var integral = integrand.ToEntity().Integrate("x"); + var allocated = GC.GetAllocatedBytesForCurrentThread() - before; + var text = integral.Stringize(); + Assert.DoesNotContain("integral(", text); + Assert.True(allocated < bytes, $"{allocated / 1e9:F2} GB to integrate {integrand}, over the {bytes / 1e9:F0} GB bound"); + Entity Pinned(Entity e) => e.Substitute("ka", 1.3).Substitute("kb", 0.7).Substitute("kc", 0.4).Substitute("kd", 0.3); + var derivative = Pinned(integral.Substitute("C", 0)).Differentiate("x"); + var original = Pinned(integrand.ToEntity()); + var compared = 0; + foreach (var at in new[] { p1, p2, p3, p4, p5, p6 }) + { + var want = original.Substitute("x", at).EvalNumerical(); + var got = derivative.Substitute("x", at).EvalNumerical(); + if (want.IsNaN) + continue; + compared++; + Assert.True(Math.Abs((double)(got - want).RealPart) + Math.Abs((double)(got - want).ImaginaryPart) + < 1e-9 * Math.Max(1, Math.Abs((double)want.RealPart) + Math.Abs((double)want.ImaginaryPart)), + $"d/dx of the antiderivative of {integrand} is {got} at x = {at}, where the integrand is {want}"); + } + Assert.True(compared >= 5, $"only {compared} points could be compared for {integrand}"); + } + + /// + /// The simplification itself, of that integrand as the substitution writes it: the form it + /// always had, for a thirtieth of the 12 GB it cost. + /// + [Fact] + public void TheTangentsIntegrandSimplifiesAsBefore() + { + var written = "(wt*1)^4/((wb*(wt*1)^2 + wa*1^2 + wa*(wt*1)^2)^2*(1 + wt^2))".ToEntity(); + var before = GC.GetAllocatedBytesForCurrentThread(); + var simplified = written.Simplify(); + var allocated = GC.GetAllocatedBytesForCurrentThread() - before; + Assert.Equal("wt ^ 4 / ((wa * (1 + wt ^ 2) + wb * wt ^ 2) ^ 2 * (wt ^ 2 + 1))", simplified.Stringize()); + Assert.True(allocated < 3_000_000_000L, $"{allocated / 1e9:F2} GB to simplify {written}"); + } + } +}