From 5c4a7d91cb5e69c713c48d15c864ebdfe3dc3dd1 Mon Sep 17 00:00:00 2001 From: Rafael Vuijk Date: Fri, 18 Sep 2026 22:33:51 +0000 Subject: [PATCH] A sum, difference, product, quotient, conjunction, disjunction, exclusive disjunction, union or intersection caches the flat list of its operands, and SimplifyHard allocates 5.2% less #224. LinearChildren flattened a nested sum or product into a lazy chain of Concat and Select enumerables, built afresh on every enumeration -- and a difference's subtracted terms were each multiplied by -1 anew, a quotient's divisor factors each raised to -1 anew -- while every rule that reads a sum as a list reads it again for every candidate. A node is immutable, so the flat list is a property of the node: it is built once, as an array, from its parts' own cached lists, and handed out as an IReadOnlyList from then on. Memory is linear in the tree, since a nested node's array is built from the arrays cached on its children rather than by walking down again, and no enumeration is repeated. The same for the five other associative chains -- and, or, xor, unite, intersect -- whose flatteners in Functions/Boolean/Simplifier.cs had the same lazy shape behind a generic branch getter, and read by the sort-and-group rules. The benchmark gate measured it: with the sum and product caches alone SimplifyHard allocates 171,275,272 B per operation against the 181,019,056 B recorded at 6e5986a7, 5.4% less, and 8.1% less than the 186,284,672 B of the commit before this one; the five connective caches put 334,536 B back (+0.2%), the arrays of chains flattened once outweighing the enumerations they save, so the whole is 171,609,808 B, 5.2% less. The other eighteen gated rows are within tolerance, ParseHard carrying the +1.6% the quantifier grammar cost in #1421. Recorded in performance-baseline.json in the same change, as the gate's own instructions say an improvement must be. Also corrects the Modf record's summary, which said the remainder takes the sign of the dividend as C#'s % does: it is the floored remainder, (-7) mod 3 is 2, as the evaluation and Syntax.md have said since #708. Closes #224. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_012sonx8iAspMiwRwokT1Ura --- .../Entity.Continuous.Operators.Classes.cs | 73 ++++++++++++++--- .../Functions/Boolean/Simplifier.cs | 66 +++++++-------- .../DotnetBenchmark/performance-baseline.json | 80 +++++++++---------- 3 files changed, 134 insertions(+), 85 deletions(-) diff --git a/Sources/AngouriMath/Core/Entity/Continuous/Entity.Continuous.Operators.Classes.cs b/Sources/AngouriMath/Core/Entity/Continuous/Entity.Continuous.Operators.Classes.cs index f25a0456b..dabbf5b0d 100644 --- a/Sources/AngouriMath/Core/Entity/Continuous/Entity.Continuous.Operators.Classes.cs +++ b/Sources/AngouriMath/Core/Entity/Continuous/Entity.Continuous.Operators.Classes.cs @@ -6,6 +6,8 @@ // using System; +using System.Collections.Generic; +using HonkSharp.Laziness; namespace AngouriMath { @@ -58,13 +60,33 @@ private Sumf New(Entity augend, Entity addend) => /// would return /// { 1, x, (-1) * a / 2, b, (-1) * 4 } /// - internal static IEnumerable LinearChildren(Entity tree) => tree switch + /// + /// Cached on the node it is asked of, since a node is immutable and the flattening + /// is asked for many times over: every rule that reads a sum as a list reads it + /// again for each candidate. A nested sum's list is built from its parts' lists, + /// which are cached on those parts, so the memory is linear in the tree and no + /// enumeration is repeated. https://github.com/asc-community/AngouriMath/issues/224 + /// + internal static IReadOnlyList LinearChildren(Entity tree) => tree switch { - Sumf(var augend, var addend) => LinearChildren(augend).Concat(LinearChildren(addend)), - Minusf(var minuend, var subtrahend) => - LinearChildren(minuend).Concat(LinearChildren(subtrahend).Select(entity => -1 * entity)), + Sumf sum => sum.Linear, + Minusf difference => difference.Linear, _ => new[] { tree } }; + + private IReadOnlyList Linear => linear.GetValue(static @this => Flatten(LinearChildren(@this.Augend), LinearChildren(@this.Addend)), this); + private LazyPropertyA> linear; + + /// The two lists as one array. + internal static Entity[] Flatten(IReadOnlyList left, IReadOnlyList right) + { + var flat = new Entity[left.Count + right.Count]; + for (var i = 0; i < left.Count; i++) + flat[i] = left[i]; + for (var i = 0; i < right.Count; i++) + flat[left.Count + i] = right[i]; + return flat; + } } /// @@ -87,6 +109,17 @@ private Minusf New(Entity minuend, Entity subtrahend) => public override Entity Replace(Func func) => func(New(Minuend.Replace(func), Subtrahend.Replace(func))); /// protected override Entity[] InitDirectChildren() => new[] { Minuend, Subtrahend }; + + /// The terms as a sum reads them: the subtrahend's terms each times -1. See . + internal IReadOnlyList Linear => linear.GetValue(static @this => + { + var subtracted = Sumf.LinearChildren(@this.Subtrahend); + var negated = new Entity[subtracted.Count]; + for (var i = 0; i < negated.Length; i++) + negated[i] = -1 * subtracted[i]; + return Sumf.Flatten(Sumf.LinearChildren(@this.Minuend), negated); + }, this); + private LazyPropertyA> linear; } /// @@ -133,13 +166,16 @@ private Mulf New(Entity multiplier, Entity multiplicand) => /// would return /// { 1, x, (a^2)^(-1), b, 4^(-1) } /// - internal static IEnumerable LinearChildren(Entity tree) => tree switch + /// Cached on the node, as is. + internal static IReadOnlyList LinearChildren(Entity tree) => tree switch { - Mulf(var multiplier, var multiplicand) => LinearChildren(multiplier).Concat(LinearChildren(multiplicand)), - Divf(var dividend, var divisor) => - LinearChildren(dividend).Concat(LinearChildren(divisor).Select(entity => new Powf(entity, -1))), + Mulf product => product.Linear, + Divf quotient => quotient.Linear, _ => new[] { tree } }; + + private IReadOnlyList Linear => linear.GetValue(static @this => Sumf.Flatten(LinearChildren(@this.Multiplier), LinearChildren(@this.Multiplicand)), this); + private LazyPropertyA> linear; } /// @@ -162,13 +198,26 @@ internal Divf New(Entity dividend, Entity divisor) => public override Entity Replace(Func func) => func(New(Dividend.Replace(func), Divisor.Replace(func))); /// protected override Entity[] InitDirectChildren() => new[] { Dividend, Divisor }; + + /// The factors as a product reads them: the divisor's factors each to the power -1. See . + internal IReadOnlyList Linear => linear.GetValue(static @this => + { + var divided = Mulf.LinearChildren(@this.Divisor); + var inverted = new Entity[divided.Count]; + for (var i = 0; i < inverted.Length; i++) + inverted[i] = new Powf(divided[i], -1); + return Sumf.Flatten(Mulf.LinearChildren(@this.Dividend), inverted); + }, this); + private LazyPropertyA> linear; } /// - /// A node of modulus, that is, the remainder after division. Follows the sign of - /// the dividend, as C#'s own % does and as - /// PeterO.Numbers does underneath: -7 % 3 is -1, - /// not 2. + /// A node of modulus, that is, the floored remainder after division, + /// a - b * floor(a / b), which takes the sign of the divisor: + /// (-7) mod 3 is 2 and 7 mod (-3) is -2, the convention of + /// SymPy, Mathematica and Maxima and the one under which the residues modulo n + /// are 0 to n - 1. Not C#'s %, which truncates; this comment said + /// the opposite of what the evaluation and the documentation do. /// public sealed partial record Modf(Entity Dividend, Entity Divisor) : ContinuousNode, IBinaryNode { diff --git a/Sources/AngouriMath/Functions/Boolean/Simplifier.cs b/Sources/AngouriMath/Functions/Boolean/Simplifier.cs index aaccc5a54..d9397fc9a 100644 --- a/Sources/AngouriMath/Functions/Boolean/Simplifier.cs +++ b/Sources/AngouriMath/Functions/Boolean/Simplifier.cs @@ -1,67 +1,67 @@ -// +// // Copyright (c) 2019-2022 Angouri. // AngouriMath is licensed under MIT. // Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md. // Website: https://am.angouri.org. // +using System.Collections.Generic; +using HonkSharp.Laziness; + namespace AngouriMath { partial record Entity { - // ngl; it looks awful - - private protected interface IBranchGetter - { - Entity Left(T node); - Entity Right(T node); - } - - private protected static IEnumerable LinearChildren(Entity expr) - where TNode : Entity where TGetter : struct, IBranchGetter - { - if (expr is not TNode node) - return new[] { expr }; - var (left, right) = (default(TGetter).Left(node), default(TGetter).Right(node)); - return LinearChildren(left).Concat(LinearChildren(right)); - } + // The flat list of a chain of one associative connective, cached on the node exactly as + // Sumf.LinearChildren and Mulf.LinearChildren are: a node is immutable, the list is a + // property of it, and a nested chain's list is built from the lists cached on its parts. + // https://github.com/asc-community/AngouriMath/issues/224 partial record Orf { - private struct OrfBranchGetter : IBranchGetter { public Entity Left(Orf node) => node.Left; public Entity Right(Orf node) => node.Right; } - internal static IEnumerable LinearChildren(Entity expr) - => LinearChildren(expr); + /// The disjuncts of a chain of or, flattened. + internal static IReadOnlyList LinearChildren(Entity expr) + => expr is Orf chain ? chain.Linear : new[] { expr }; + private IReadOnlyList Linear => linear.GetValue(static @this => Sumf.Flatten(LinearChildren(@this.Left), LinearChildren(@this.Right)), this); + private LazyPropertyA> linear; } partial record Andf { - private struct AndfBranchGetter : IBranchGetter { public Entity Left(Andf node) => node.Left; public Entity Right(Andf node) => node.Right; } - internal static IEnumerable LinearChildren(Entity expr) - => LinearChildren(expr); + /// The conjuncts of a chain of and, flattened. + internal static IReadOnlyList LinearChildren(Entity expr) + => expr is Andf chain ? chain.Linear : new[] { expr }; + private IReadOnlyList Linear => linear.GetValue(static @this => Sumf.Flatten(LinearChildren(@this.Left), LinearChildren(@this.Right)), this); + private LazyPropertyA> linear; } partial record Xorf { - private struct XorfBranchGetter : IBranchGetter { public Entity Left(Xorf node) => node.Left; public Entity Right(Xorf node) => node.Right; } - internal static IEnumerable LinearChildren(Entity expr) - => LinearChildren(expr); - + /// The operands of a chain of xor, flattened. + internal static IReadOnlyList LinearChildren(Entity expr) + => expr is Xorf chain ? chain.Linear : new[] { expr }; + private IReadOnlyList Linear => linear.GetValue(static @this => Sumf.Flatten(LinearChildren(@this.Left), LinearChildren(@this.Right)), this); + private LazyPropertyA> linear; } partial record Set { partial record Unionf { - private struct UnionfBranchGetter : IBranchGetter { public Entity Left(Unionf node) => node.Left; public Entity Right(Unionf node) => node.Right; } - internal static IEnumerable LinearChildren(Entity expr) - => LinearChildren(expr); + /// The sets of a chain of unions, flattened. + internal static IReadOnlyList LinearChildren(Entity expr) + => expr is Unionf chain ? chain.Linear : new[] { expr }; + private IReadOnlyList Linear => linear.GetValue(static @this => Sumf.Flatten(LinearChildren(@this.Left), LinearChildren(@this.Right)), this); + private LazyPropertyA> linear; } partial record Intersectionf { - private struct IntersectionfBranchGetter : IBranchGetter { public Entity Left(Intersectionf node) => node.Left; public Entity Right(Intersectionf node) => node.Right; } - internal static IEnumerable LinearChildren(Entity expr) - => LinearChildren(expr); + /// The sets of a chain of intersections, flattened. + internal static IReadOnlyList LinearChildren(Entity expr) + => expr is Intersectionf chain ? chain.Linear : new[] { expr }; + private IReadOnlyList Linear => linear.GetValue(static @this => Sumf.Flatten(LinearChildren(@this.Left), LinearChildren(@this.Right)), this); + private LazyPropertyA> linear; } } } diff --git a/Sources/Tests/DotnetBenchmark/performance-baseline.json b/Sources/Tests/DotnetBenchmark/performance-baseline.json index 86a0ad1b9..8ce33a2b8 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": "6e5986a79fdc06992b8a825dbc921f0950b0a2c2", - "measuredOn": "2026-09-16", + "commit": "86af5774", + "measuredOn": "2026-09-18", "runtime": ".NET 10.0.10", "machine": "Ubuntu 26.04 LTS, X64, 8 logical cores", "cases": { "CompileEasy": { - "allocatedBytes": 11047, - "meanNanoseconds": 204705.0737109375 + "allocatedBytes": 11031, + "meanNanoseconds": 185188.89744466144 }, "CompileHard": { - "allocatedBytes": 20434, - "meanNanoseconds": 328377.93669782364 + "allocatedBytes": 20578, + "meanNanoseconds": 310618.45002092636 }, "Derivate": { - "allocatedBytes": 53528, - "meanNanoseconds": 16009.772457427978 + "allocatedBytes": 54567, + "meanNanoseconds": 14042.05355529785 }, "EvalEasy": { "allocatedBytes": 0, - "meanNanoseconds": 1.9644719183977162 + "meanNanoseconds": 1.886511587848266 }, "EvalPolynomialFresh": { - "allocatedBytes": 12424, - "meanNanoseconds": 4162.247797648112 + "allocatedBytes": 12488, + "meanNanoseconds": 4182.401444498698 }, "EvalPolynomialFresh15Digits": { - "allocatedBytes": 11752, - "meanNanoseconds": 4420.195562882857 + "allocatedBytes": 11816, + "meanNanoseconds": 4230.6761957804365 }, "EvalTranscendentalFresh": { - "allocatedBytes": 34688, - "meanNanoseconds": 17244.48943721887 + "allocatedBytes": 34720, + "meanNanoseconds": 16170.0028522198 }, "EvalTrig": { - "allocatedBytes": 69872, - "meanNanoseconds": 36505.40553977273 + "allocatedBytes": 69904, + "meanNanoseconds": 32002.166080729166 }, "EvalTrigPrecise": { - "allocatedBytes": 336440, - "meanNanoseconds": 428454.6749173678 + "allocatedBytes": 336472, + "meanNanoseconds": 406349.3584735577 }, "ParseEasy": { - "allocatedBytes": 18205, - "meanNanoseconds": 6093.238420213972 + "allocatedBytes": 18405, + "meanNanoseconds": 6233.427952902658 }, "ParseHard": { - "allocatedBytes": 3555346, - "meanNanoseconds": 1761245.3062065972 + "allocatedBytes": 3611690, + "meanNanoseconds": 1402665.6583333334 }, "RunEasy": { "allocatedBytes": 0, - "meanNanoseconds": 21.0467557828216 + "meanNanoseconds": 20.38737736940384 }, "RunHard": { "allocatedBytes": 0, - "meanNanoseconds": 296.7305618066054 + "meanNanoseconds": 299.6865839958191 }, "RunMedium": { "allocatedBytes": 0, - "meanNanoseconds": 164.83484596865517 + "meanNanoseconds": 163.13498663902283 }, "SimplifyEasy": { - "allocatedBytes": 78802, - "meanNanoseconds": 47969.87247258967 + "allocatedBytes": 79026, + "meanNanoseconds": 44808.87176949637 }, "SimplifyHard": { - "allocatedBytes": 181019056, - "meanNanoseconds": 128834309.01041667 + "allocatedBytes": 171609808, + "meanNanoseconds": 103780529.86666666 }, "SolveEasy": { - "allocatedBytes": 453364, - "meanNanoseconds": 221822.51813083224 + "allocatedBytes": 452941, + "meanNanoseconds": 202519.96311442056 }, "SolveEasyMedium": { - "allocatedBytes": 65602, - "meanNanoseconds": 19954.031829833984 + "allocatedBytes": 65770, + "meanNanoseconds": 19068.897886812018 }, "SolveHard": { - "allocatedBytes": 10118288, - "meanNanoseconds": 77972042.29347827 + "allocatedBytes": 10143512, + "meanNanoseconds": 70150981.74509804 }, "SolveMedium": { - "allocatedBytes": 449581, - "meanNanoseconds": 336183.44418304134 + "allocatedBytes": 451845, + "meanNanoseconds": 271962.3498722957 }, "SolveMediumHard": { - "allocatedBytes": 1382724, - "meanNanoseconds": 8940742.8125 + "allocatedBytes": 1393396, + "meanNanoseconds": 8300025.078125 } }, "ungated": {