|
| 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 AngouriMath.Core.Budgets; |
| 9 | +using AngouriMath.Core.Exceptions; |
| 10 | +using System; |
| 11 | +using static AngouriMath.Entity; |
| 12 | +using static AngouriMath.Entity.Number; |
| 13 | +using static AngouriMath.Entity.Set; |
| 14 | + |
| 15 | +namespace AngouriMath.Functions.Algebra.AnalyticalSolving |
| 16 | +{ |
| 17 | + /// <summary> |
| 18 | + /// A system with more or fewer equations than unknowns that neither the triangularisation nor |
| 19 | + /// <see cref="LinearSystemSolver"/> takes, such as <c>x^2 + y^2 = 1</c> for <c>x</c> and |
| 20 | + /// <c>y</c>, or <c>sin(x) = 0</c> and <c>x = 0</c> for <c>x</c>. Each unknown is eliminated in |
| 21 | + /// turn, an unknown that nothing is left to constrain becomes a parameter, and every family |
| 22 | + /// found is substituted back into every equation. |
| 23 | + /// <a href="https://github.com/asc-community/AngouriMath/issues/212">#212</a> |
| 24 | + /// </summary> |
| 25 | + /// <remarks> |
| 26 | + /// <para> |
| 27 | + /// <b>An answer is given only where it is shown to hold.</b> The elimination trusts each solve |
| 28 | + /// it makes, and a solve can answer for a case its equation does not cover: <c>sqrt(y) = x</c> |
| 29 | + /// is solved for <c>y</c> as <c>x^2</c>, which is no solution where <c>x</c> is negative. So |
| 30 | + /// each family is kept only where every equation, with the family substituted, simplifies to |
| 31 | + /// <c>0</c>. <c>sqrt(t^2) - t</c> does not, and that system is declined. |
| 32 | + /// </para> |
| 33 | + /// <para> |
| 34 | + /// <b>A decline declines the whole system.</b> An equation left with no unknown in it is zero, |
| 35 | + /// a number away from zero, or neither as far as can be told, like <c>(a + b)/2 - c</c>. A |
| 36 | + /// branch where one is away from zero has no solutions and is dropped. A branch where one |
| 37 | + /// cannot be told gives no answer for the system, rather than leaving the other branches to |
| 38 | + /// read as all of its solutions. |
| 39 | + /// </para> |
| 40 | + /// <para> |
| 41 | + /// A square system does not come here. It is the eliminator's in |
| 42 | + /// <see cref="EquationSolver.InSolveSystem"/>, whose answers this would change. |
| 43 | + /// </para> |
| 44 | + /// </remarks> |
| 45 | + internal static class NonSquareSystemSolver |
| 46 | + { |
| 47 | + /// <summary> |
| 48 | + /// The solutions of <paramref name="equations"/> in <paramref name="variables"/>, a list of |
| 49 | + /// values in their order for each family, or <see langword="null"/> where none were found. |
| 50 | + /// </summary> |
| 51 | + internal static List<List<Entity>>? Solve(List<Entity> equations, Variable[] variables, BudgetLedger ledger) |
| 52 | + { |
| 53 | + // One parameter per unknown that is left free, the same in every branch. Each is |
| 54 | + // minted against the equations and the parameters already minted, since CreateUnique |
| 55 | + // compares whole names in use and would otherwise hand back the same name twice. |
| 56 | + var parameters = new Variable?[variables.Length]; |
| 57 | + Entity nameSource = equations.Count > 0 ? Sumf.Sum(equations) : Integer.Zero; |
| 58 | + Variable ParameterFor(int index) |
| 59 | + { |
| 60 | + if (parameters[index] is { } minted) |
| 61 | + return minted; |
| 62 | + var parameter = Variable.CreateUnique(nameSource, "t"); |
| 63 | + nameSource += parameter; |
| 64 | + return parameters[index] = parameter; |
| 65 | + } |
| 66 | + |
| 67 | + if (Eliminate(equations, variables, variables.Length, ParameterFor, ledger) is not { Count: > 0 } families) |
| 68 | + return null; |
| 69 | + foreach (var family in families) |
| 70 | + foreach (var equation in equations) |
| 71 | + { |
| 72 | + var substituted = equation; |
| 73 | + for (var index = 0; index < variables.Length; index++) |
| 74 | + substituted = substituted.Substitute(variables[index], family[index]); |
| 75 | + if (!Vanishes(substituted)) |
| 76 | + return null; |
| 77 | + } |
| 78 | + return families; |
| 79 | + } |
| 80 | + |
| 81 | + /// <summary> |
| 82 | + /// The solutions in the first <paramref name="count"/> of <paramref name="variables"/>, each |
| 83 | + /// a list of their values in order. Empty where there are none, and |
| 84 | + /// <see langword="null"/> where that could not be told. |
| 85 | + /// </summary> |
| 86 | + private static List<List<Entity>>? Eliminate(List<Entity> equations, Variable[] variables, int count, |
| 87 | + Func<int, Variable> parameterFor, BudgetLedger ledger) |
| 88 | + { |
| 89 | + // Charged as InSolveSystem charges it: one unit for each candidate explored. |
| 90 | + if (!ledger.Spend()) |
| 91 | + throw new NotSufficientlySupportedException( |
| 92 | + "this system of equations is not solvable within the budget. Raise " |
| 93 | + + "MathS.Settings.Budget to allow more, or pass a cancellation token with " |
| 94 | + + "MathS.Multithreading.SetLocalCancellationToken"); |
| 95 | + |
| 96 | + // No unknown is left, so each equation holds as it stands or does not. |
| 97 | + if (count == 0) |
| 98 | + { |
| 99 | + var told = true; |
| 100 | + foreach (var equation in equations) |
| 101 | + switch (Holds(equation)) |
| 102 | + { |
| 103 | + case false: |
| 104 | + return new(); |
| 105 | + case null: |
| 106 | + told = false; |
| 107 | + break; |
| 108 | + } |
| 109 | + return told ? new() { new() } : null; |
| 110 | + } |
| 111 | + |
| 112 | + // No equation is left, so every unknown left is free. |
| 113 | + if (equations.Count == 0) |
| 114 | + { |
| 115 | + var free = new List<Entity>(); |
| 116 | + for (var index = 0; index < count; index++) |
| 117 | + free.Add(parameterFor(index)); |
| 118 | + return new() { free }; |
| 119 | + } |
| 120 | + |
| 121 | + var variable = variables[count - 1]; |
| 122 | + // The equation with the fewest occurrences of the unknown first, which is solved by |
| 123 | + // inverting it and has the plainest roots: of `cos(x) = sin(x)` and `x = pi/4`, the |
| 124 | + // first is solved as ln(sqrt(i))/i and the second as pi/4. |
| 125 | + var candidates = Enumerable.Range(0, equations.Count) |
| 126 | + .Where(i => equations[i].ContainsNode(variable)) |
| 127 | + .OrderBy(i => equations[i].Nodes.Count(node => node == variable)) |
| 128 | + .ThenBy(i => equations[i].Complexity) |
| 129 | + .ToList(); |
| 130 | + foreach (var i in candidates) |
| 131 | + { |
| 132 | + // An empty set is passed over as InSolveSystem passes it over: substituting an |
| 133 | + // earlier unknown can leave an occurrence that cancels, and then the solve has |
| 134 | + // nothing to say about this one. |
| 135 | + if (equations[i].SolveEquation(variable).InnerSimplified is not FiniteSet roots || roots.Count == 0) |
| 136 | + continue; |
| 137 | + var rest = new List<Entity>(equations); |
| 138 | + rest.RemoveAt(i); |
| 139 | + if (EachRoot(roots, rest, variables, count, parameterFor, ledger) is { } solutions) |
| 140 | + return solutions; |
| 141 | + // This equation's roots left a question that could not be told. Another |
| 142 | + // equation's may not: `sin(x) = 0` gives x = 2 pi n_1, where `x = 0` gives 0. |
| 143 | + } |
| 144 | + |
| 145 | + if (candidates.Count > 0) |
| 146 | + return null; |
| 147 | + // Nothing constrains this unknown, so it is a parameter in every solution of the rest. |
| 148 | + var others = Eliminate(equations, variables, count - 1, parameterFor, ledger); |
| 149 | + others?.ForEach(family => family.Add(parameterFor(count - 1))); |
| 150 | + return others; |
| 151 | + } |
| 152 | + |
| 153 | + /// <summary> |
| 154 | + /// The solutions where the last of the unknowns is each of <paramref name="roots"/> in |
| 155 | + /// turn, or <see langword="null"/> where that could not be told for one of them. |
| 156 | + /// </summary> |
| 157 | + private static List<List<Entity>>? EachRoot(FiniteSet roots, List<Entity> rest, Variable[] variables, int count, |
| 158 | + Func<int, Variable> parameterFor, BudgetLedger ledger) |
| 159 | + { |
| 160 | + var variable = variables[count - 1]; |
| 161 | + var solutions = new List<List<Entity>>(); |
| 162 | + foreach (var root in roots) |
| 163 | + { |
| 164 | + var substituted = rest.Select(equation => equation.Substitute(variable, root)).ToList(); |
| 165 | + if (Eliminate(substituted, variables, count - 1, parameterFor, ledger) is not { } families) |
| 166 | + return null; |
| 167 | + foreach (var family in families) |
| 168 | + { |
| 169 | + var value = root; |
| 170 | + for (var index = 0; index < count - 1; index++) |
| 171 | + value = value.Substitute(variables[index], family[index]); |
| 172 | + family.Add(value.InnerSimplified); |
| 173 | + solutions.Add(family); |
| 174 | + } |
| 175 | + } |
| 176 | + return solutions; |
| 177 | + } |
| 178 | + |
| 179 | + /// <summary> |
| 180 | + /// Whether <paramref name="equation"/>, with no unknown left in it, holds: |
| 181 | + /// <see langword="true"/> where it simplifies to zero, <see langword="false"/> where it is a |
| 182 | + /// number away from zero, and <see langword="null"/> where neither can be told. |
| 183 | + /// </summary> |
| 184 | + private static bool? Holds(Entity equation) |
| 185 | + { |
| 186 | + if (Vanishes(equation)) |
| 187 | + return true; |
| 188 | + if (equation.Vars.Any() || equation.Evaled is not Complex value || value.IsNaN) |
| 189 | + return null; |
| 190 | + // An exact number that is not zero is not zero. A decimal is taken as away from zero |
| 191 | + // only well past the digits its evaluation may have lost. |
| 192 | + if (value is Rational) |
| 193 | + return false; |
| 194 | + return ((Real)value.Abs()).EDecimal.ToDouble() > 1e-9 ? false : null; |
| 195 | + } |
| 196 | + |
| 197 | + /// <summary> |
| 198 | + /// Whether <paramref name="expression"/> is zero for every value of its symbols: zero as it |
| 199 | + /// is evaluated, or simplified to zero. A simplification to <c>0 provided C</c> counts only |
| 200 | + /// where <c>C</c> holds with the symbols pinned, since <c>t - c (t/c)</c> simplifies to |
| 201 | + /// <c>0 provided not c = 0</c> for a <c>c</c> that is zero without being written |
| 202 | + /// <c>0</c>, such as <c>(a + 1)^2 - a^2 - 2a - 1</c>. |
| 203 | + /// </summary> |
| 204 | + private static bool Vanishes(Entity expression) |
| 205 | + { |
| 206 | + if (expression.InnerSimplified.Evaled is Complex { IsZero: true }) |
| 207 | + return true; |
| 208 | + // Away from zero at a point is not zero everywhere, which settles most without |
| 209 | + // simplifying. |
| 210 | + if (Pinned(expression).Evaled is Complex { IsNaN: false } atAPoint |
| 211 | + && ((Real)atAPoint.Abs()).EDecimal.ToDouble() > 1e-9) |
| 212 | + return false; |
| 213 | + return expression.Simplify() switch |
| 214 | + { |
| 215 | + Providedf(var simplified, var condition) => |
| 216 | + simplified.Evaled is Complex { IsZero: true } && Pinned(condition).Evaled is Entity.Boolean { Value: true }, |
| 217 | + var simplified => simplified.Evaled is Complex { IsZero: true }, |
| 218 | + }; |
| 219 | + } |
| 220 | + |
| 221 | + /// <summary><paramref name="expression"/> with each of its symbols at a fixed value.</summary> |
| 222 | + private static Entity Pinned(Entity expression) |
| 223 | + { |
| 224 | + var values = new[] { 1.37, 0.61, 2.23, 1.91, 0.83, 1.13 }; |
| 225 | + var index = 0; |
| 226 | + foreach (var symbol in expression.Vars.ToList()) |
| 227 | + expression = expression.Substitute(symbol, values[index++ % values.Length]); |
| 228 | + return expression; |
| 229 | + } |
| 230 | + } |
| 231 | +} |
0 commit comments