|
| 1 | +// |
| 2 | +// Copyright (c) 2019-2026 Angouri. |
| 3 | +// AngouriMath is licensed under MIT. |
| 4 | +// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md. |
| 5 | +// Website: https://am.angouri.org. |
| 6 | +// |
| 7 | + |
| 8 | +using System.Collections.Generic; |
| 9 | +using System.Linq; |
| 10 | +using PeterO.Numbers; |
| 11 | +using static AngouriMath.Entity; |
| 12 | +using static AngouriMath.Entity.Number; |
| 13 | +using static AngouriMath.Entity.Set; |
| 14 | + |
| 15 | +namespace AngouriMath.Functions |
| 16 | +{ |
| 17 | + /// <summary> |
| 18 | + /// The image of a set of reals under a quotient of polynomials, <c>{ f(x) : x in S }</c>, read |
| 19 | + /// off the function's critical points and its limits: Sullivan and Mackey's §7.3.5 Try 1, |
| 20 | + /// <c>x/(1 + x)</c> over <c>RR \ {-1}</c>, is <c>RR \ {1}</c>, and Prob 7.8.8's |
| 21 | + /// <c>(2x - 1)/(2x (1 - x))</c> over <c>(0, 1)</c> is <c>RR</c>. |
| 22 | + /// </summary> |
| 23 | + /// <remarks> |
| 24 | + /// <para> |
| 25 | + /// A continuous function maps an interval onto an interval, and a differentiable one is |
| 26 | + /// monotone between the zeros of its derivative, so the image of an interval without a pole is |
| 27 | + /// the interval between the least and the greatest of the values at the critical points inside |
| 28 | + /// it, the values at its closed ends and the one-sided limits at its open ones. An end of the |
| 29 | + /// image is closed where the value is taken, at a critical point or a closed end, and open |
| 30 | + /// where it is only approached. The set is cut into such intervals first: at the points a |
| 31 | + /// difference removes, and at the poles, where the function is not defined. |
| 32 | + /// </para> |
| 33 | + /// <para> |
| 34 | + /// The derivative's zeros have to be all of them, or a turning point is missed and the image |
| 35 | + /// comes out too small. So the numerator of the derivative, and the denominator whose zeros |
| 36 | + /// are the poles, have to be polynomials of degree four or less, which the solver answers in |
| 37 | + /// radicals completely; the coefficients have to be rational, so that a coefficient which |
| 38 | + /// cancels is zero rather than a residue; and every root has to evaluate, a real one to a |
| 39 | + /// candidate and a non-real one to nothing. A real root can come out of the radicals with an |
| 40 | + /// imaginary residue near <c>1e-99</c>, which is read as zero below the downcasting tolerance |
| 41 | + /// whether downcasting is on or not. |
| 42 | + /// </para> |
| 43 | + /// https://github.com/asc-community/AngouriMath/issues/1409 |
| 44 | + /// </remarks> |
| 45 | + internal static class ImageByCalculus |
| 46 | + { |
| 47 | + /// <summary>The highest degree whose roots the solver lists completely, in radicals.</summary> |
| 48 | + private const int MaxDegree = 4; |
| 49 | + |
| 50 | + /// <summary>The largest whole exponent read, so that nothing large is expanded to find a degree.</summary> |
| 51 | + private const int MaxExponent = 8; |
| 52 | + |
| 53 | + internal static Set? Of(Entity f, Variable x, Entity over) |
| 54 | + { |
| 55 | + if (!f.ContainsNode(x) || !IsRational(f, x) || Pieces(over) is not { } pieces) |
| 56 | + return null; |
| 57 | + var (numerator, denominator) = SingleQuotient.Of(f); |
| 58 | + // The quotient rule's numerator: its zeros are the critical points. |
| 59 | + var slope = numerator.Differentiate(x) * denominator - numerator * denominator.Differentiate(x); |
| 60 | + if (Polynomial(denominator, x) is not { } bottom || Polynomial(slope, x) is not { } top |
| 61 | + || RealRoots(bottom, x) is not { } poles || RealRoots(top, x) is not { } critical) |
| 62 | + return null; |
| 63 | + // Each piece's image once, from the left, so that the union reads in order and two |
| 64 | + // pieces with one image are written once. |
| 65 | + var parts = new List<(Set Part, Real From)>(); |
| 66 | + foreach (var piece in pieces.SelectMany(piece => CutAt(piece, poles))) |
| 67 | + { |
| 68 | + if (Of(f, x, piece, critical) is not { } part) |
| 69 | + return null; |
| 70 | + if (Lowest(part) is { } from && parts.All(other => other.Part != part)) |
| 71 | + parts.Add((part, from)); |
| 72 | + } |
| 73 | + Set image = Empty; |
| 74 | + foreach (var (part, _) in parts.OrderBy(part => part.From)) |
| 75 | + image = image.Unite(part).InnerSimplified is Set united ? united : (Set)image.Unite(part); |
| 76 | + return image; |
| 77 | + } |
| 78 | + |
| 79 | + /// <summary>Where an image of one piece starts, or <see langword="null"/> for an empty one.</summary> |
| 80 | + private static Real? Lowest(Set part) |
| 81 | + => part switch |
| 82 | + { |
| 83 | + Interval interval => AsReal(interval.Left), |
| 84 | + FiniteSet { Count: > 0 } listed => AsReal(listed.First()), |
| 85 | + _ => null, |
| 86 | + }; |
| 87 | + |
| 88 | + /// <summary>The image of one interval with no pole inside.</summary> |
| 89 | + private static Set? Of(Entity f, Variable x, Interval piece, List<(Entity Root, Real Value)> critical) |
| 90 | + { |
| 91 | + if (AsReal(piece.Left) is not { } left || AsReal(piece.Right) is not { } right) |
| 92 | + return null; |
| 93 | + if (left.CompareTo(right) > 0 || left == right && !(piece.LeftClosed && piece.RightClosed)) |
| 94 | + return Empty; |
| 95 | + // Each candidate is a value, what it evaluates to, and whether it is taken. |
| 96 | + var candidates = new List<(Entity Value, Real Number, bool Taken)>(); |
| 97 | + foreach (var (root, at) in critical) |
| 98 | + if (at.CompareTo(left) > 0 && at.CompareTo(right) < 0) |
| 99 | + { |
| 100 | + var value = f.Substitute(x, root); |
| 101 | + if (AsReal(value) is not { IsFinite: true } number) |
| 102 | + return null; |
| 103 | + candidates.Add((value, number, true)); |
| 104 | + } |
| 105 | + if (End(f, x, piece.Left, left, piece.LeftClosed, Core.ApproachFrom.Right) is not { } atLeft |
| 106 | + || End(f, x, piece.Right, right, piece.RightClosed, Core.ApproachFrom.Left) is not { } atRight) |
| 107 | + return null; |
| 108 | + candidates.Add(atLeft); |
| 109 | + candidates.Add(atRight); |
| 110 | + var least = candidates.Min(candidate => candidate.Number)!; |
| 111 | + var greatest = candidates.Max(candidate => candidate.Number)!; |
| 112 | + // Only the two that bound the image are simplified. |
| 113 | + var lower = candidates.First(candidate => Same(candidate.Number, least)).Value.Simplify(); |
| 114 | + var upper = candidates.First(candidate => Same(candidate.Number, greatest)).Value.Simplify(); |
| 115 | + var lowerTaken = least.IsFinite && candidates.Any(candidate => Same(candidate.Number, least) && candidate.Taken); |
| 116 | + var upperTaken = greatest.IsFinite && candidates.Any(candidate => Same(candidate.Number, greatest) && candidate.Taken); |
| 117 | + // A function constant on the interval takes its one value at every point of it. |
| 118 | + if (Same(least, greatest)) |
| 119 | + return new FiniteSet(lower); |
| 120 | + return new Interval(lower, lowerTaken, upper, upperTaken); |
| 121 | + } |
| 122 | + |
| 123 | + /// <summary>The value at a closed end, taken, or the one-sided limit at an open one, approached.</summary> |
| 124 | + private static (Entity Value, Real Number, bool Taken)? End(Entity f, Variable x, Entity end, Real at, bool closed, Core.ApproachFrom side) |
| 125 | + { |
| 126 | + if (closed && at.IsFinite) |
| 127 | + { |
| 128 | + var value = f.Substitute(x, end); |
| 129 | + return AsReal(value) is { IsFinite: true } number ? (value, number, true) : null; |
| 130 | + } |
| 131 | + // A limit that is not found stays a limit node, which does not evaluate to a number. |
| 132 | + var limit = at.IsFinite ? f.Limit(x, end, side) : f.Limit(x, end); |
| 133 | + return AsReal(limit) is { IsNaN: false } approached ? (limit, approached, false) : null; |
| 134 | + } |
| 135 | + |
| 136 | + /// <summary> |
| 137 | + /// The expression as a polynomial of degree at most <see cref="MaxDegree"/>, its monomials |
| 138 | + /// gathered and those that cancel dropped, or <see langword="null"/>. |
| 139 | + /// </summary> |
| 140 | + private static Entity? Polynomial(Entity expr, Variable x) |
| 141 | + { |
| 142 | + if (!TreeAnalyzer.TryGetPolynomial(expr, x, out var monomials)) |
| 143 | + return null; |
| 144 | + Entity sum = Integer.Zero; |
| 145 | + foreach (var monomial in monomials) |
| 146 | + { |
| 147 | + var power = monomial.Key; |
| 148 | + if (monomial.Value.Evaled is not Rational exact) |
| 149 | + return null; |
| 150 | + if (exact.IsZero) |
| 151 | + continue; |
| 152 | + if (power.Sign < 0 || power.CompareTo(EInteger.FromInt32(MaxDegree)) > 0) |
| 153 | + return null; |
| 154 | + // The constant term as itself: x^0 is 1 only where x is not 0. |
| 155 | + sum += power.IsZero ? exact : exact * MathS.Pow(x, Integer.Create(power)); |
| 156 | + } |
| 157 | + return sum.InnerSimplified; |
| 158 | + } |
| 159 | + |
| 160 | + /// <summary> |
| 161 | + /// The real roots of a polynomial with each one's value, or <see langword="null"/> where the |
| 162 | + /// solver does not list them all as numbers. |
| 163 | + /// </summary> |
| 164 | + private static List<(Entity Root, Real Value)>? RealRoots(Entity polynomial, Variable x) |
| 165 | + { |
| 166 | + if (!polynomial.ContainsNode(x)) |
| 167 | + return new List<(Entity, Real)>(); |
| 168 | + // The equation solver answers a polynomial it cannot list with a set that is not |
| 169 | + // listed, rather than throwing. |
| 170 | + if (polynomial.SolveEquation(x) is not FiniteSet listed) |
| 171 | + return null; |
| 172 | + var real = new List<(Entity, Real)>(); |
| 173 | + foreach (var root in listed) |
| 174 | + if (AsReal(root) is { } value) |
| 175 | + { |
| 176 | + if (!value.IsFinite) |
| 177 | + return null; |
| 178 | + real.Add((root, value)); |
| 179 | + } |
| 180 | + else if (root.Evaled is not Complex { RealPart.IsFinite: true, ImaginaryPart.IsFinite: true }) |
| 181 | + return null; |
| 182 | + return real; |
| 183 | + } |
| 184 | + |
| 185 | + /// <summary> |
| 186 | + /// What the expression evaluates to as a real number, or <see langword="null"/> where it is |
| 187 | + /// not one. An imaginary part below the downcasting tolerance is the residue of exact |
| 188 | + /// cancellation and is read as zero, as downcasting would read it. |
| 189 | + /// </summary> |
| 190 | + private static Real? AsReal(Entity expr) |
| 191 | + => expr.Evaled switch |
| 192 | + { |
| 193 | + Real real => real, |
| 194 | + Complex complex when complex.ImaginaryPart.EDecimal.IsFinite |
| 195 | + && complex.ImaginaryPart.EDecimal.Abs().LessThan(MathS.Settings.DowncastingTolerance) => complex.RealPart, |
| 196 | + _ => null, |
| 197 | + }; |
| 198 | + |
| 199 | + /// <summary>Two values that differ by less than the downcasting tolerance are one.</summary> |
| 200 | + private static bool Same(Real a, Real b) |
| 201 | + => a == b || a.IsFinite && b.IsFinite && (a - b).EDecimal.Abs().LessThan(MathS.Settings.DowncastingTolerance); |
| 202 | + |
| 203 | + /// <summary>The set as intervals, or <see langword="null"/> where it is not a union of intervals and points removed.</summary> |
| 204 | + private static List<Interval>? Pieces(Entity over) |
| 205 | + => over switch |
| 206 | + { |
| 207 | + SpecialSet.Reals => new List<Interval> { new Interval(Real.NegativeInfinity, false, Real.PositiveInfinity, false) }, |
| 208 | + Interval interval => new List<Interval> { interval }, |
| 209 | + Unionf(var left, var right) => Pieces(left) is { } l && Pieces(right) is { } r ? l.Concat(r).ToList() : null, |
| 210 | + SetMinusf(var from, FiniteSet removed) when removed.All(point => AsReal(point) is { IsFinite: true }) |
| 211 | + => Pieces(from) is { } pieces ? pieces.SelectMany(piece => CutAt(piece, removed.Select(point => (point, AsReal(point)!)).ToList())).ToList() : null, |
| 212 | + _ => null, |
| 213 | + }; |
| 214 | + |
| 215 | + /// <summary>The interval cut open at each of the points inside it.</summary> |
| 216 | + private static IEnumerable<Interval> CutAt(Interval piece, List<(Entity Root, Real Value)> points) |
| 217 | + { |
| 218 | + if (AsReal(piece.Left) is not { } left || AsReal(piece.Right) is not { } right) |
| 219 | + return new[] { piece }; |
| 220 | + var inside = points.Where(point => point.Value.CompareTo(left) > 0 && point.Value.CompareTo(right) < 0) |
| 221 | + .OrderBy(point => point.Value).ToList(); |
| 222 | + if (inside.Count == 0) |
| 223 | + return new[] { piece }; |
| 224 | + var cut = new List<Interval>(); |
| 225 | + Entity from = piece.Left; |
| 226 | + var fromClosed = piece.LeftClosed; |
| 227 | + foreach (var (root, _) in inside) |
| 228 | + { |
| 229 | + cut.Add(new Interval(from, fromClosed, root, false)); |
| 230 | + (from, fromClosed) = (root, false); |
| 231 | + } |
| 232 | + cut.Add(new Interval(from, fromClosed, piece.Right, piece.RightClosed)); |
| 233 | + return cut; |
| 234 | + } |
| 235 | + |
| 236 | + /// <summary> |
| 237 | + /// Whether the expression is built from the variable, rational constants and the four |
| 238 | + /// operations with whole powers no larger than <see cref="MaxExponent"/>. |
| 239 | + /// </summary> |
| 240 | + private static bool IsRational(Entity f, Variable x) |
| 241 | + => f switch |
| 242 | + { |
| 243 | + _ when !f.ContainsNode(x) => f.Evaled is Rational, |
| 244 | + Variable => true, |
| 245 | + Sumf(var a, var b) => IsRational(a, x) && IsRational(b, x), |
| 246 | + Minusf(var a, var b) => IsRational(a, x) && IsRational(b, x), |
| 247 | + Mulf(var a, var b) => IsRational(a, x) && IsRational(b, x), |
| 248 | + Divf(var a, var b) => IsRational(a, x) && IsRational(b, x), |
| 249 | + Powf(var a, Integer power) when power.EInteger.Abs().CompareTo(EInteger.FromInt32(MaxExponent)) <= 0 => IsRational(a, x), |
| 250 | + _ => false, |
| 251 | + }; |
| 252 | + } |
| 253 | +} |
0 commit comments