Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions Sources/.editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -1129,3 +1129,9 @@ file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed

[Tests/UnitTests/Convenience/ShadersTest.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/Core/Entity/Entity.Nodes.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

[Tests/UnitTests/Core/NodesWalkTest.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
9 changes: 5 additions & 4 deletions Sources/AngouriMath/Core/Entity/Entity.Definition.cs
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,9 @@ public virtual bool Equals(Entity? other)
internal virtual IReadOnlyList<Entity> MatchableChildren => DirectChildren;

/// <remarks>A depth-first enumeration is required by
/// <see cref="AngouriMath.Functions.TreeAnalyzer.GetMinimumSubtree"/></remarks>
/// <see cref="AngouriMath.Functions.TreeAnalyzer.GetMinimumSubtree"/>. Nothing is cached:
/// each enumeration walks the tree afresh, at the cost of one object and none per node
/// (see <see cref="NodeWalk"/>).</remarks>
/// <summary>
/// The list of all subnodes of the given expression, including its own. Traverses
/// the tree the following order:
Expand All @@ -212,8 +214,7 @@ public virtual bool Equals(Entity? other)
/// 3
/// </code>
/// </example>
public IEnumerable<Entity> Nodes => nodes.GetValue(static @this => @this.DirectChildren.SelectMany(c => c.Nodes).Prepend(@this), this);
private LazyPropertyA<IEnumerable<Entity>> nodes;
public IEnumerable<Entity> Nodes => new NodeWalk(this);

/// <summary>
/// Applies the given function to every node starting from the leaves
Expand Down Expand Up @@ -775,7 +776,7 @@ private static IReadOnlyCollection<Variable> BoundBy(Entity binder, params Entit
/// True
/// </code>
/// </example>
public bool ContainsNode(Entity x) => x is Variable v ? VarsAndConsts.Contains(v) : Nodes.Contains(x);
public bool ContainsNode(Entity x) => x is Variable v ? VarsAndConsts.Contains(v) : WalkFinds(x);

/// <summary>
/// Implicit conversation from string to Entity. See <see cref="MathS.FromString(string,bool)"/>
Expand Down
216 changes: 216 additions & 0 deletions Sources/AngouriMath/Core/Entity/Entity.Nodes.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,216 @@
//
// 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.Buffers;
using System.Collections;
using System.Collections.Generic;

namespace AngouriMath
{
partial record Entity
{
/// <summary>Whether any node, this one included, satisfies <paramref name="predicate"/>,
/// asked in the order of <see cref="Nodes"/> and stopping at the first; what
/// <c>Nodes.Any(predicate)</c> answers, without allocating.</summary>
internal bool AnyNode(Func<Entity, bool> predicate)
{
var walk = new NodeStack(this);
try
{
while (walk.MoveNext())
if (predicate(walk.Current))
return true;
return false;
}
finally { walk.Release(); }
}

/// <summary>What <c>Nodes.All(predicate)</c> answers, without allocating.</summary>
internal bool AllNodes(Func<Entity, bool> predicate)
{
var walk = new NodeStack(this);
try
{
while (walk.MoveNext())
if (!predicate(walk.Current))
return false;
return true;
}
finally { walk.Release(); }
}

/// <summary>What <c>Nodes.Contains(node)</c> answers, without allocating.</summary>
private bool WalkFinds(Entity node)
{
var walk = new NodeStack(this);
try
{
while (walk.MoveNext())
if (walk.Current == node)
return true;
return false;
}
finally { walk.Release(); }
}

/// <summary>How many nodes, this one included, are equal to <paramref name="node"/>.</summary>
internal int CountNode(Entity node)
{
var walk = new NodeStack(this);
try
{
var count = 0;
while (walk.MoveNext())
if (walk.Current == node)
count++;
return count;
}
finally { walk.Release(); }
}

/// <summary>
/// The pre-order walk behind <see cref="Nodes"/>: the node, then each child's walk in
/// order, kept on an explicit stack rented from <see cref="ArrayPool{T}.Shared"/>.
/// </summary>
/// <remarks>
/// <para>
/// It allocates nothing, per node or per walk, and keeps nothing on the tree. A chain of
/// LINQ iterators costs an iterator per node per enumeration, and caching it on every
/// node keeps that chain alive as long as the node; caching the walk's result instead is
/// quadratic in memory, since every node would hold its whole subtree (31 MB on a sum of
/// 2000 terms).
/// <a href="https://github.com/asc-community/AngouriMath/issues/534">#534</a>
/// </para>
/// <para>
/// Every walk has its own stack, so a predicate that walks another tree while this one
/// is being walked, on this thread or another, shares nothing with it. A walk that is
/// abandoned without <see cref="Release"/> only fails to give its array back to the
/// pool. It is a mutable struct: copying one mid-walk would share the array, so it is
/// only ever held in a local or in <see cref="NodeWalk"/>.
/// </para>
/// </remarks>
private struct NodeStack
{
private Entity? next;
private Entity? current;
private Entity[]? stack;
private int count;

internal NodeStack(Entity root)
{
next = root;
current = null;
stack = null;
count = 0;
}

internal readonly Entity Current => current!;

internal bool MoveNext()
{
if (next is not null)
{
current = next;
next = null;
return true;
}
if (current is null)
return false;
// The children of the node just yielded are pushed only now, so a walk stopped
// at a node never asks for its children.
var children = current.DirectChildren;
if (children.Count > 0)
{
Reserve(children.Count);
for (var i = children.Count - 1; i >= 0; i--)
stack![count++] = children[i];
}
if (count == 0)
{
Release();
return false;
}
current = stack![--count];
stack[count] = null!;
return true;
}

private void Reserve(int more)
{
if (stack is null)
stack = ArrayPool<Entity>.Shared.Rent(Math.Max(16, more));
else if (count + more > stack.Length)
{
var larger = ArrayPool<Entity>.Shared.Rent(Math.Max(2 * stack.Length, count + more));
Array.Copy(stack, larger, count);
Array.Clear(stack, 0, count);
ArrayPool<Entity>.Shared.Return(stack);
stack = larger;
}
}

internal void Release()
{
if (stack is not null)
{
// The pool hands the array to the next renter, which must not keep this
// tree alive through it.
Array.Clear(stack, 0, count);
ArrayPool<Entity>.Shared.Return(stack);
stack = null;
}
count = 0;
next = null;
current = null;
}
}

/// <summary>
/// <see cref="NodeStack"/> as the <see cref="IEnumerable{T}"/> that <see cref="Nodes"/>
/// publishes, at one object per enumeration.
/// </summary>
private sealed class NodeWalk : IEnumerable<Entity>, IEnumerator<Entity>
{
private readonly Entity root;
private readonly int ownerThread;
private bool handedOut;
private NodeStack walk;

internal NodeWalk(Entity root)
{
this.root = root;
ownerThread = Environment.CurrentManagedThreadId;
walk = new NodeStack(root);
}

// The first enumeration on the thread that asked for Nodes is this object itself, as
// LINQ's own iterators do, so the common Nodes.Any(...) costs one object, not two.
public IEnumerator<Entity> GetEnumerator()
{
if (!handedOut && ownerThread == Environment.CurrentManagedThreadId)
{
handedOut = true;
return this;
}
return new NodeWalk(root) { handedOut = true };
}

IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();

public Entity Current => walk.Current;

object IEnumerator.Current => Current;

public bool MoveNext() => walk.MoveNext();

public void Dispose() => walk.Release();

public void Reset() => throw new NotSupportedException();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -61,12 +61,12 @@ public static Entity GetMinimumSubtree(Entity expr, Variable x)
// The idea is the following:
// We must get a subtree that has more occurances than 1,
// But at the same time it should cover all references to `ent`
var xs = expr.Nodes.Count(child => child == x);
var xs = expr.CountNode(x);
return
expr.Nodes
.TakeWhile(e => e != x) // Requires Entity enumeration to be depth-first!!
.Where(e => e.ContainsNode(x)) // e.g. when expr is sin((x+1)^2)+3, this step results in [sin((x+1)^2)+3, sin((x+1)^2), (x+1)^2, x+1]
.LastOrDefault(sub => expr.Nodes.Count(child => child == sub) * sub.Nodes.Count(child => child == x) == xs)
.LastOrDefault(sub => expr.CountNode(sub) * sub.CountNode(x) == xs)
// if `expr` contains 2 `sub`s and `sub` contains 3 `x`s, then there should be 6 `x`s in `expr` (6 == `xs`)
?? x;
}
Expand Down
24 changes: 12 additions & 12 deletions Sources/AngouriMath/Functions/Simplification/Simplificator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ internal static Entity Simplify(Entity expr, int level)
// one has no runs before it. See simplifications. Not while a limit reads an
// approach, on which logarithms gather that do not gather on their own account:
// the same tree simplified on two approaches, or on one and on none, is two answers.
if (simplifying == 1 || RewriteRecording.Current is not null || !expr.Nodes.All(IsElementary)
if (simplifying == 1 || RewriteRecording.Current is not null || !expr.AllNodes(IsElementary)
|| Algebra.LimitFunctional.IsReadingAnApproach)
return SimplifyAtDepth(expr, level);
var kept = simplifications ??= new();
Expand Down Expand Up @@ -140,7 +140,7 @@ internal static Entity Simplify(Entity expr, int level)
/// </summary>
internal static Entity Expanded(Entity expr)
{
if (simplifying == 0 || RewriteRecording.Current is not null || !expr.Nodes.All(IsElementary))
if (simplifying == 0 || RewriteRecording.Current is not null || !expr.AllNodes(IsElementary))
return expr.Expand();
var kept = expansions ??= new();
if (kept.TryGetValue(expr, out var known) && Convenience.SettingsState.StillHolds(known.Under))
Expand Down Expand Up @@ -447,11 +447,11 @@ void __IterAddHistory(Entity expr)
// the same -- and a tie is settled by whichever candidate came first, which
// is an accident rather than a preference.
// https://github.com/asc-community/AngouriMath/issues/205
if (res.Nodes.Any(child => child is Divf))
if (res.AnyNode(child => child is Divf))
AddHistory(res = Simplified(recording, res.Rewrite(RewriteRules.RationalizeDenominator)));

res = Simplified(recording, res.Rewrite(RewriteRules.CanonicalOrderAt(sortLevel)));
if (res.Nodes.Any(child => child is Powf))
if (res.AnyNode(child => child is Powf))
AddHistory(res = Simplified(recording, res.Rewrite(RewriteRules.Power)));

AddHistory(res = SimplifyChildren(res));
Expand All @@ -464,7 +464,7 @@ void __IterAddHistory(Entity expr)
// 3x^2 (u + 2)^2 / (3x^2) is (u + 2)^2, which the rules below reach as it
// stands, and u^2 + 4u + 4 only once this has expanded it. The complexity
// metric is what should decide between them.
if (res.Nodes.Any(child => child is Divf))
if (res.AnyNode(child => child is Divf))
AddHistory(Simplified(recording, res.Rewrite(RewriteRules.PolynomialGcdCancellation)));

AddHistory(res = Simplified(recording, res.Rewrite(RewriteRules.PolynomialLongDivision)));
Expand All @@ -478,7 +478,7 @@ void __IterAddHistory(Entity expr)
AddHistory(res = Simplified(recording, res.Rewrite(RewriteRules.Trigonometric)));
AddHistory(res = Simplified(recording, res.Rewrite(RewriteRules.CollapseTrigonometricFunctions)));

if (res.Nodes.Any(child => child is TrigonometricFunction))
if (res.AnyNode(child => child is TrigonometricFunction))
{
// The Pythagorean pair found anywhere in a sum -- the binary rule above sees
// it only where the sort has made it a node. Inside this block, since the
Expand Down Expand Up @@ -509,38 +509,38 @@ void __IterAddHistory(Entity expr)
}


if (res.Nodes.Any(child => child is Statement))
if (res.AnyNode(child => child is Statement))
{
AddHistory(res = Simplified(recording, res.Rewrite(RewriteRules.Boolean)));
}


if (res.Nodes.Any(child => child is ComparisonSign))
if (res.AnyNode(child => child is ComparisonSign))
{
AddHistory(res = Simplified(recording, res.Rewrite(RewriteRules.InequalityEquality)));
}

// A binomial coefficient is three factorials, and its identities live in the
// gathering set. https://github.com/asc-community/AngouriMath/issues/1409
if (res.Nodes.Any(child => child is Factorialf or Binomialf))
if (res.AnyNode(child => child is Factorialf or Binomialf))
{
AddHistory(res = Simplified(recording, res.Rewrite(RewriteRules.ExpandFactorialDivisions)));
AddHistory(res = Simplified(recording, res.Rewrite(RewriteRules.FactorizeFactorialMultiplications)));
}


if (res.Nodes.Any(child => child is Powf or Logf))
if (res.AnyNode(child => child is Powf or Logf))
AddHistory(res = Simplified(recording, res.Rewrite(RewriteRules.Power)));

if (res.Nodes.Any(child => child is Set))
if (res.AnyNode(child => child is Set))
{
var replaced = res.Rewrite(RewriteRules.SetOperator);

AddHistory(res = Simplified(recording, replaced));
}


if (res.Nodes.Any(child => child is Phif))
if (res.AnyNode(child => child is Phif))
AddHistory(res = Simplified(recording, res.Rewrite(RewriteRules.PhiFunction)));

Entity? possiblePoly = null;
Expand Down
Loading