diff --git a/AGENTS.md b/AGENTS.md index badb5ce..38999ac 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -26,8 +26,9 @@ generated parser, on netstandard2.0): keep it so, and keep containers and other | `samples/SharpEquations.WinForms.Demo/` | A form with the editor of `SharpEquations.WinForms` (Windows) | | `samples/SharpEquations.Avalonia.Browser.Demo/` | The same demo on WebAssembly (needs the `wasm-tools` workload, so not in the solution; `.github/workflows/demo.yml` publishes it to GitHub Pages) | | `samples/SharpEquations.Avalonia.MathTools.Demo/` | A second app, math tools around the editor, in MVVM: the view models (`ViewModels/`: `MathToolsViewModel` and one for each page, over a small `ObservableObject` and `RelayCommand`, no package; the tests drive them) and the views in AXAML with compiled bindings (`Views/`: `MathToolsView`, with the brushes, the styles and the `Card` of the pages, a page each: the scientific keypad, the library of formulas, whose Graph button draws a formula on the graphs page, the unit converter, the solver of triangles, the graphs: `GraphsPage` on a `GraphView`, a slider for each parameter; the graphs in space: `Graphs3DPage` on a `Graph3DView`, OpenGL through Silk.NET where there is a context and the Skia painter elsewhere, in the browser too; the worksheet: `WorksheetPage`) and the desktop window | -| `samples/SharpEquations.MathTools.Core/` | The math tools without a user interface: `ICasEngine` (`AngouriMathEngine`, through `MathReader`, which reads what the normalized presentation MathML means: in radians or degrees, systems of equations, definitions `a≔5`), the formulas (a `GraphPreset` for those with a graph: the equation drawn and its parameters at their starting values, Greek letters too), the units (NIST factors) and triangles, the equations of the graphs in space (`SurfacePlot`: z=f(x,y) or a curve x,y,z of t, with their parameters), the `Worksheet` (the history of what was computed, kept as JSON in the settings, its definitions made again when it is read back), and the services the views ask the platform for (`ISettingsStore`: a file on the desktop, the local storage in the browser) | +| `samples/SharpEquations.MathTools.Core/` | The math tools without a user interface: `ICasEngine` (`AngouriMathEngine`, through `MathReader`, which reads what the normalized presentation MathML means: in radians or degrees, systems of equations, definitions `a≔5`; `Series` sums to infinity the quotients of polynomials AngouriMath leaves as they are, by partial fractions over `Polynomial`s of `Fraction`s), the formulas (a `GraphPreset` for those with a graph: the equation drawn and its parameters at their starting values, Greek letters too), the units (NIST factors) and triangles, the equations of the graphs in space (`SurfacePlot`: z=f(x,y) or a curve x,y,z of t, with their parameters), the `Worksheet` (the history of what was computed, kept as JSON in the settings, its definitions made again when it is read back), and the services the views ask the platform for (`ISettingsStore`: a file on the desktop, the local storage in the browser) | | `samples/SharpEquations.MathTools.Graphing/` | The graphs of the math tools without a user interface: the region shown (`Viewport`), the marks of the axes, the points of a curve (`Sampler`: closer where it bends, broken at asymptotes and steps) and where a relation of x and y holds (`Contours`); in space, the meshes and curves in a cube (`Scene3D`), the camera turning around it (`OrbitCamera`) and the painter's algorithm that draws them without a graphics card (`Painter3D`) | +| `samples/SharpEquations.MathTools.MathEngine/` | An optional adapter of the engine of Microsoft Mathematics (`mathenginen.dll`, never in this repository: looked for in `MATHENGINEN_PATH`, else in the program files) as an `ICasEngine`, to compare its results with AngouriMath; `MathEngineText` writes its linear input and reads its results without the library. Windows only, the library of the processor of the process; its reference tests are skipped elsewhere | | `samples/SharpEquations.Avalonia.Browser.MathTools.Demo/` | The math tools on WebAssembly (as the web demo, not in the solution build; `demo.yml` publishes them under `math/`) | | `benchmarks/SharpEquations.Benchmarks/` | BenchmarkDotNet benchmarks of reading, writing and converting the corpora | | `tests/SharpEquations.Tests/` | TUnit tests, in folders by subject (PublicApi, MathML, Omml, Mtef, UnicodeMath, LaTeX, Property, Regression) | @@ -35,7 +36,7 @@ generated parser, on netstandard2.0): keep it so, and keep containers and other | `tests/SharpEquations.Uno.Tests/` | TUnit tests of the controls of `SharpEquations.Uno` in a real Uno app on the desktop (`Program` starts the app, then runs TUnit; the tests work on its thread through `Ui.Run`); it needs a display: `xvfb-run` on Linux | | `tests/SharpEquations.Wpf.Tests/` | TUnit tests of the controls of `SharpEquations.Wpf` in a window on a thread of its own (`Ui`: STA, with its dispatcher); they build everywhere and run on Windows only | | `tests/SharpEquations.WinForms.Tests/` | TUnit tests of the controls of `SharpEquations.WinForms` in a form on a thread of its own (`Ui`: STA, with its message loop); they build everywhere and run on Windows only | -| `tests/SharpEquations.MathTools.Tests/` | TUnit tests of `SharpEquations.MathTools.Core` and `.Graphing` (net10.0), with the reference tests of the computer algebra and the units (`tests/data/mathtools/`: cases compared by their value, the ones not reached yet `pending` with the reason; a change makes no passing case fail) | +| `tests/SharpEquations.MathTools.Tests/` | TUnit tests of `SharpEquations.MathTools.Core`, `.Graphing` and `.MathEngine` (net10.0), with the reference tests of the computer algebra and the units (`tests/data/mathtools/`: cases compared by their value, the ones not reached yet `pending` with the reason; a change makes no passing case fail) | | `tests/data/` | Test data and its provenance (`tests/data/README.md`) | ## Code Style diff --git a/Directory.Packages.props b/Directory.Packages.props index 6d9c582..a0e3e59 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -31,6 +31,7 @@ + diff --git a/SharpEquations.slnx b/SharpEquations.slnx index 954f993..fb1d5b0 100644 --- a/SharpEquations.slnx +++ b/SharpEquations.slnx @@ -11,6 +11,7 @@ + diff --git a/samples/SharpEquations.MathTools.Core/Cas/AngouriMathEngine.cs b/samples/SharpEquations.MathTools.Core/Cas/AngouriMathEngine.cs index 44631c5..1cd5e27 100644 --- a/samples/SharpEquations.MathTools.Core/Cas/AngouriMathEngine.cs +++ b/samples/SharpEquations.MathTools.Core/Cas/AngouriMathEngine.cs @@ -77,6 +77,7 @@ private static List Variables(IEnumerable expressions) => /// Does an action to an expression of AngouriMath. public static CasResult Run(CasAction action, Entity expression, string? variable) { + expression = Series.Close(expression); var letters = Variables(expression); var x = MathS.Var(variable ?? (letters.Count > 0 ? letters[0] : "x")); switch (action) @@ -260,6 +261,9 @@ private static IReadOnlyList Equations(IEnumerable values) return equations; } + /// An expression of AngouriMath as an equation (through its LaTeX), or null when it cannot be written. + public static Equation? ToEquation(Entity value) => Parse(Latex(value)); + private static Equation? Parse(string latex) => Equation.TryParse(latex, EquationFormat.LaTeX, new EquationOptions { Display = true }, out var parsed) && !parsed!.ToMathML().Descendants().Any(e => e.Name.LocalName == "merror") diff --git a/samples/SharpEquations.MathTools.Core/Cas/Series.cs b/samples/SharpEquations.MathTools.Core/Cas/Series.cs new file mode 100644 index 0000000..047c1ec --- /dev/null +++ b/samples/SharpEquations.MathTools.Core/Cas/Series.cs @@ -0,0 +1,631 @@ +namespace SharpEquations.MathTools +{ + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + using System.Numerics; + using AngouriMath; + + /// + /// The sums to infinity that AngouriMath leaves as they are, when the term is a quotient of polynomials of the index + /// with fractions as coefficients, P(k)/Q(k), or one with the sign of (−1)ᵏ: + /// + /// the quotient is split in partial fractions c/(k−r)ʲ over the fractions r that are roots of Q; + /// those with j = 1 sum to values of the digamma function at fractions, which the theorem of Gauss writes with + /// π and logarithms: ln 2 for (−1)ᵏ⁺¹/k, π/4 for (−1)ᵏ/(2k+1), 1 for 1/(k(k+1)); + /// those with j > 1 sum to values of ζ(j, x): a fraction times πʲ for an even j at 1 and 1/2 (π²/6 for 1/k², + /// by the Bernoulli numbers), and for any j at x and 1 − x together, by the derivatives of the cotangent (π³/32 for + /// (−1)ᵏ/(2k+1)³); + /// a factor k² + bk + c of Q with no such roots, with b whole and a number over it, sums by the residues of + /// π cot πz: (π coth π − 1)/2 for 1/(k²+1); + /// a sum with the sign of (−1)ᵏ is the sum of its even terms less that of its odd ones; + /// a term that does not go to zero fast enough has a sum with no end, ∞ or −∞. + /// + /// A factor of the term without the index is taken out, and a sum of terms is the sum of their sums, when each has + /// one (also by AngouriMath, as a geometric one). What is not of these forms, or has no such value (ζ(3) for 1/k³), + /// is left as it is. + /// + public static class Series + { + private const int MostTerms = 5000; + + private const int MostDenominator = 360; + + private const int MostPower = 64; + + private static readonly BigInteger MostCoefficient = BigInteger.Pow(10, 12); + + private static readonly Fraction Half = new Fraction(1, 2); + + /// The expression with each sum to infinity that has a known value replaced by it. + public static Entity Close(Entity expression) => + expression.Nodes.Any(n => n is Entity.Summationf) ? expression.Replace(e => e is Entity.Summationf sum ? Value(sum) ?? e : e) : expression; + + /// The value of a sum to infinity of a known form, or null. + public static Entity? Value(Entity.Summationf sum) + { + if (sum.To != MathS.oo || sum.Var is not Entity.Variable k || sum.From is not Entity.Number.Integer from + || !from.EInteger.CanFitInInt64() || sum.Expression.Vars.Any(v => v != k)) + return null; + var start = from.EInteger.ToInt64Checked(); + return Value(sum.Expression, k, start) ?? Split(sum.Expression, k, start); + } + + // a sum of terms, each with its own sum (also by AngouriMath, as a geometric one) + private static Entity? Split(Entity body, Entity.Variable k, long start) + { + var parts = new List(); + Terms(body, parts, 1); + if (parts.Count < 2) + return null; + Entity total = 0; + foreach (var part in parts) + { + var value = Value(part, k, start) ?? MathS.Sum(part, k, start, MathS.oo).Simplify(); + if (value.Nodes.Any(n => n is Entity.Summationf || n == MathS.oo || n == -MathS.oo)) + return null; + total += value; + } + return total; + } + + private static void Terms(Entity e, List parts, int sign) + { + switch (e) + { + case Entity.Sumf s: + Terms(s.Augend, parts, sign); + Terms(s.Addend, parts, sign); + break; + case Entity.Minusf m: + Terms(m.Minuend, parts, sign); + Terms(m.Subtrahend, parts, -sign); + break; + default: + parts.Add(sign > 0 ? e : -e); + break; + } + } + + private static Entity? Value(Entity body, Entity.Variable k, long start) + { + if (Read(body, k) is { } term) + return Sum(term.Plain, term.Alternating, start); + if (Peel(body, k) is not { } peeled || Value(peeled.Term, k, start) is not { } value) + return null; + if (value != MathS.oo && value != -MathS.oo) + return peeled.Constant * value; + return Sign(peeled.Constant) switch + { + > 0 => value, + < 0 => value == MathS.oo ? -MathS.oo : MathS.oo, + _ => null, + }; + } + + // a factor without the index, and the rest + private static (Entity Constant, Entity Term)? Peel(Entity body, Entity.Variable k) => body switch + { + Entity.Mulf m when Free(m.Multiplier, k) => (m.Multiplier, m.Multiplicand), + Entity.Mulf m when Free(m.Multiplicand, k) => (m.Multiplicand, m.Multiplier), + Entity.Divf d when Free(d.Divisor, k) => (1 / d.Divisor, d.Dividend), + Entity.Divf d when Free(d.Dividend, k) && d.Dividend is not Entity.Number => (d.Dividend, 1 / d.Divisor), + Entity.Divf d when Peel(d.Divisor, k) is { } divisor => (1 / divisor.Constant, d.Dividend / divisor.Term), + _ => null, + }; + + private static bool Free(Entity e, Entity.Variable k) => !e.Vars.Contains(k); + + private static int Sign(Entity constant) + { + try + { + return constant.EvalNumerical() is Entity.Number.Real real ? real.EDecimal.Sign : 0; + } + catch (AngouriMath.Core.Exceptions.AngouriMathBaseException) + { + return 0; + } + } + + // the term as plain(k) + (−1)ᵏ alternating(k), when it is made of fractions, the index, the four operations, whole + // powers and powers of −1 + private static (RationalFunction Plain, RationalFunction Alternating)? Read(Entity e, Entity.Variable k) + { + switch (e) + { + case Entity.Number.Rational number: + return (Constant(ToFraction(number)), RationalFunction.Zero); + case Entity.Variable v when v == k: + return (new RationalFunction(Polynomial.X, Polynomial.One), RationalFunction.Zero); + case Entity.Sumf s when Read(s.Augend, k) is { } x && Read(s.Addend, k) is { } y: + return (x.Plain + y.Plain, x.Alternating + y.Alternating); + case Entity.Minusf s when Read(s.Minuend, k) is { } x && Read(s.Subtrahend, k) is { } y: + return (x.Plain - y.Plain, x.Alternating - y.Alternating); + case Entity.Mulf m when Read(m.Multiplier, k) is { } x && Read(m.Multiplicand, k) is { } y: + return Multiply(x, y); + case Entity.Divf d when Read(d.Dividend, k) is { } x && Read(d.Divisor, k) is { } y: + return Divide(x, y); + case Entity.Powf p when Free(p.Exponent, k): + if (Whole(p.Exponent) is not { } power || Math.Abs(power) > MostPower || Read(p.Base, k) is not { } b) + return null; + var result = (Plain: Constant(Fraction.One), Alternating: RationalFunction.Zero); + for (var i = 0; i < Math.Abs(power); i++) + result = Multiply(result, b); + return power < 0 ? Divide((Constant(Fraction.One), RationalFunction.Zero), result) : result; + case Entity.Powf p when Free(p.Base, k) && Whole(p.Base) == -1 && Read(p.Exponent, k) is { } exponent: + var line = exponent.Plain.Numerator; + if (!exponent.Alternating.IsZero || exponent.Plain.Denominator.Degree != 0 || line.Degree > 1 + || !line[0].IsInteger || !line[1].IsInteger) + return null; + var sign = Constant(line[0].Numerator.IsEven ? 1 : -1); + return line[1].Numerator.IsEven ? (sign, RationalFunction.Zero) : (RationalFunction.Zero, sign); + default: + return null; + } + } + + // (−1)ᵏ times itself is 1 + private static (RationalFunction Plain, RationalFunction Alternating) Multiply( + (RationalFunction Plain, RationalFunction Alternating) x, (RationalFunction Plain, RationalFunction Alternating) y) => + (x.Plain * y.Plain + x.Alternating * y.Alternating, x.Plain * y.Alternating + x.Alternating * y.Plain); + + private static (RationalFunction Plain, RationalFunction Alternating)? Divide( + (RationalFunction Plain, RationalFunction Alternating) x, (RationalFunction Plain, RationalFunction Alternating) y) + { + if (y.Alternating.IsZero) + return y.Plain.IsZero ? null : (x.Plain / y.Plain, x.Alternating / y.Plain); + if (y.Plain.IsZero) + return (x.Alternating / y.Alternating, x.Plain / y.Alternating); + var norm = y.Plain * y.Plain - y.Alternating * y.Alternating; + if (norm.IsZero) + return null; + return ((x.Plain * y.Plain - x.Alternating * y.Alternating) / norm, (x.Alternating * y.Plain - x.Plain * y.Alternating) / norm); + } + + private static RationalFunction Constant(Fraction value) => new RationalFunction(Polynomial.Constant(value), Polynomial.One); + + private static Fraction ToFraction(Entity.Number.Rational number) => new Fraction( + BigInteger.Parse(number.ERational.Numerator.ToString(), CultureInfo.InvariantCulture), + BigInteger.Parse(number.ERational.Denominator.ToString(), CultureInfo.InvariantCulture)); + + private static long? Whole(Entity e) => + e.Evaled is Entity.Number.Integer whole && whole.EInteger.CanFitInInt64() ? whole.EInteger.ToInt64Checked() : (long?)null; + + // ∑_(k≥start) plain(k) + (−1)ᵏ alternating(k) + private static Entity? Sum(RationalFunction plain, RationalFunction alternating, long start) + { + var total = new Combination(); + if (!alternating.IsZero) + { + // the terms have to go to zero; then the even ones less the odd ones, as a sum over m with k = start + 2m + if (alternating.Gap < 1 || Decompose(alternating, start) is not { } parts) + return null; + var sign = start % 2 == 0 ? 1 : -1; + var halved = new Parts(); + foreach (var (c, root, power) in parts.Poles) + { + var scale = c * Half.Pow(power) * sign; + halved.Poles.Add((scale, (root - start) * Half, power)); + halved.Poles.Add((-scale, (root - start - 1) * Half, power)); + } + foreach (var (beta, b, c) in parts.Quadratics) + { + for (var odd = 0; odd <= 1; odd++) + { + Fraction first = start + odd; + var scale = beta * new Fraction(odd == 0 ? sign : -sign, 4); + halved.Quadratics.Add((scale, first + b * Half, (first * first + b * first + c) * new Fraction(1, 4))); + } + } + if (!Add(total, halved, 0)) + return null; + } + if (!plain.IsZero) + { + if (plain.Gap < 2) + return Defined(plain, start) ? (plain.Numerator.Leading.Sign > 0 ? MathS.oo : -MathS.oo) : null; + if (Decompose(plain, start) is not { } parts || !Add(total, parts, start)) + return null; + } + return total.Value(); + } + + // whether the quotient is a number at each index of the sum + private static bool Defined(RationalFunction r, long start) => + Roots(r.Denominator) is { } factors && !factors.Roots.Any(f => f.Root.IsInteger && f.Root >= start); + + // the partial fractions of a quotient, when its denominator has only fractions as roots but for one factor of + // degree 2, and no root is an index of the sum + private static Parts? Decompose(RationalFunction r, long start) + { + if (Roots(r.Denominator) is not { } factors || (factors.Left.Degree != 0 && factors.Left.Degree != 2)) + return null; + var parts = new Parts(); + var rest = r; + foreach (var (root, multiplicity) in factors.Roots) + { + if (root.IsInteger && root >= start) + return null; + + // the first coefficients of the quotient as a series in k − root + var numerator = r.Numerator.Compose(Fraction.One, root); + var others = r.Denominator.DivRem(Polynomial.Linear(root).Pow(multiplicity)).Quotient.Compose(Fraction.One, root); + var series = new Fraction[multiplicity]; + for (var n = 0; n < multiplicity; n++) + { + var coefficient = numerator[n]; + for (var i = 1; i <= n; i++) + coefficient -= others[i] * series[n - i]; + series[n] = coefficient / others[0]; + } + for (var power = 1; power <= multiplicity; power++) + { + var c = series[multiplicity - power]; + if (c.IsZero) + continue; + parts.Poles.Add((c, root, power)); + rest -= new RationalFunction(Polynomial.Constant(c), Polynomial.Linear(root).Pow(power)); + } + } + if (factors.Left.Degree == 0) + return rest.IsZero ? parts : null; + if (rest.Denominator.Degree != 2 || rest.Numerator.Degree != 0) + return null; + parts.Quadratics.Add((rest.Numerator[0], rest.Denominator[1], rest.Denominator[0])); + return parts; + } + + // the roots of a polynomial that are fractions, and what is left of it without them + private static (List<(Fraction Root, int Multiplicity)> Roots, Polynomial Left)? Roots(Polynomial q) + { + var roots = new List<(Fraction Root, int Multiplicity)>(); + var rest = q; + var zero = 0; + for (; rest.Degree > 0 && rest[0].IsZero; zero++) + rest = rest.DivRem(Polynomial.X).Quotient; + if (zero > 0) + roots.Add((Fraction.Zero, zero)); + if (rest.Degree < 1) + return (roots, rest); + + // such a root is a divisor of the last coefficient over one of the first, once they are whole + var common = BigInteger.One; + for (var i = 0; i <= rest.Degree; i++) + common = common / BigInteger.GreatestCommonDivisor(common, rest[i].Denominator) * rest[i].Denominator; + if (Divisors(BigInteger.Abs((rest[0] * common).Numerator)) is not { } last + || Divisors(BigInteger.Abs((rest.Leading * common).Numerator)) is not { } first) + return null; + foreach (var p in last) + { + foreach (var d in first) + { + if (!BigInteger.GreatestCommonDivisor(p, d).IsOne) + continue; + foreach (var candidate in new[] { new Fraction(p, d), new Fraction(-p, d) }) + { + var multiplicity = 0; + for (; rest.Degree > 0 && rest.Evaluate(candidate).IsZero; multiplicity++) + rest = rest.DivRem(Polynomial.Linear(candidate)).Quotient; + if (multiplicity > 0) + roots.Add((candidate, multiplicity)); + } + } + } + return (roots, rest); + } + + private static List? Divisors(BigInteger n) + { + if (n.IsZero || n > MostCoefficient) + return null; + var divisors = new List { BigInteger.One }; + var left = (ulong)n; + for (ulong prime = 2; prime * prime <= left; prime++) + { + var count = divisors.Count; + BigInteger power = 1; + while (left % prime == 0) + { + left /= prime; + power *= prime; + for (var i = 0; i < count; i++) + divisors.Add(divisors[i] * power); + } + } + if (left > 1) + { + var count = divisors.Count; + for (var i = 0; i < count; i++) + divisors.Add(divisors[i] * left); + } + return divisors; + } + + // adds ∑_(k≥start) of the partial fractions, whose terms in 1/k cancel; false when it has no value in closed form + private static bool Add(Combination total, Parts parts, long start) + { + // ∑_(k≥start) c/(k−r)ʲ is −c ψ(x) for j = 1 and c ζ(j, x) for the others, at x = start − r; x is brought + // between 0 and 1 by taking the first terms away, or putting them back + var hurwitz = new Dictionary<(int Power, Fraction At), Fraction>(); + foreach (var (c, root, power) in parts.Poles) + { + var x = start - root; + var whole = -(-x).Floor() - 1; + if (BigInteger.Abs(whole) > MostTerms) + return false; + var at = x - whole; + var head = Fraction.Zero; + for (var i = Math.Min((long)whole, 0); i < Math.Max((long)whole, 0); i++) + { + if ((at + i).IsZero) + return false; + head += (at + i).Pow(-power); + } + total.Add(whole.Sign >= 0 ? -c * head : c * head); + if (power > 1) + hurwitz[(power, at)] = (hurwitz.TryGetValue((power, at), out var sum) ? sum : Fraction.Zero) + c; + else if (!Digamma(total, at, -c)) + return false; + } + + foreach (var entry in hurwitz) + { + var (power, at) = entry.Key; + var a = entry.Value; + if (a.IsZero) + continue; + Entity pi = MathS.Pow(MathS.pi, power); + if (at == Fraction.One || at == Half) + { + // ζ(j) and ζ(j, 1/2) = (2ʲ − 1) ζ(j) + if (power % 2 == 1) + return false; + total.Add(a * (at == Half ? BigInteger.Pow(2, power) - 1 : BigInteger.One) * ZetaOfEven(power), pi); + continue; + } + + // ζ(j, x) + (−1)ʲ ζ(j, 1−x) = (−1)ʲ⁻¹ π dʲ⁻¹/dxʲ⁻¹ cot πx / (j−1)! + var mirror = Fraction.One - at; + var b = hurwitz.TryGetValue((power, mirror), out var other) ? other : Fraction.Zero; + if (b != (power % 2 == 0 ? a : -a)) + return false; + if (at > mirror) + continue; + if (at.Denominator > MostDenominator) + return false; + var derivative = CotangentDerivative(power - 1); + var scale = (power % 2 == 0 ? -a : a) / Factorial(power - 1); + var (cot, irrational, square) = Cotangent(at); + if (square == 0) + { + Entity polynomial = 0; + for (var i = 0; i < derivative.Length; i++) + if (!derivative[i].IsZero) + polynomial += ((Fraction)derivative[i]).Entity * MathS.Pow(irrational!, i); + total.Add(scale, pi, polynomial); + continue; + } + var even = Fraction.Zero; + var odd = Fraction.Zero; + for (var i = 0; i < derivative.Length; i++) + { + var term = derivative[i] * cot.Pow(i) * BigInteger.Pow(square, i / 2); + if (i % 2 == 0) + even += term; + else + odd += term; + } + total.Add(scale * even, pi); + total.Add(scale * odd, pi, irrational); + } + + // ∑_(k≥start) β/(k² + bk + c), by ψ(1−z) − ψ(z) = π cot πz at the roots: half the sum over all the whole + // numbers, less (or plus) the terms between the two halves + foreach (var (beta, b, c) in parts.Quadratics) + { + if (!b.IsInteger) + return false; + var span = 2 * start + b.Numerator; + if (BigInteger.Abs(span) > MostTerms) + return false; + var quadratic = new Polynomial(new[] { c, b, Fraction.One }); + var between = Fraction.Zero; + for (var i = span.Sign > 0 ? 1 : (long)span; i <= (span.Sign > 0 ? (long)span - 1 : 0); i++) + between += Fraction.One / quadratic.Evaluate(start - i); + total.Add((span.Sign > 0 ? -beta : beta) * Half * between); + + var discriminant = b * b - 4 * c; + var quarter = (discriminant.Sign < 0 ? -discriminant : discriminant) * new Fraction(1, 4); + var rational = quarter.SquareRoot(); + Entity half = rational?.Entity ?? MathS.Sqrt(quarter.Entity); + var angle = MathS.pi * half; + var function = (discriminant.Sign < 0, span.IsEven) switch + { + (true, true) => MathS.Hyperbolic.Cotanh(angle), + (true, false) => MathS.Hyperbolic.Tanh(angle), + (false, true) => -MathS.Cotan(angle), + (false, false) => MathS.Tan(angle), + }; + if (rational is { } root) + total.Add(beta * Half / root, MathS.pi, function); + else + total.Add(beta * Half, MathS.pi, function / half); + } + return true; + } + + // adds weight·ψ(p/q), by the theorem of Gauss: + // ψ(p/q) = −γ − ln 2q − π/2 cot(πp/q) + 2 ∑_(0 MostDenominator) + return false; + var p = (long)at.Numerator; + var q = (long)at.Denominator; + var left = 2 * q; + for (long prime = 2; left > 1; prime++) + for (; left % prime == 0; left /= prime) + total.Add(-weight, MathS.Ln(prime)); + var (cot, irrational, _) = Cotangent(at); + total.Add(-weight * Half * cot, MathS.pi, irrational); + for (long n = 1; 2 * n < q; n++) + { + var (cos, cosine) = Cosine(new Fraction(n * p, q)); + foreach (var (coefficient, logarithm) in LogSine(new Fraction(n, q))) + total.Add(2 * weight * cos * coefficient, cosine, logarithm); + } + return true; + } + + // cot πx as a fraction times 1, √3 (whose square is given) or the cotangent itself (square 0) + private static (Fraction Value, Entity? Irrational, int Square) Cotangent(Fraction x) + { + switch ((int)x.Numerator, (int)x.Denominator) + { + case (1, 2): return (Fraction.Zero, null, 1); + case (1, 4): return (Fraction.One, null, 1); + case (3, 4): return (Fraction.MinusOne, null, 1); + case (1, 3): return (new Fraction(1, 3), MathS.Sqrt(3), 3); + case (2, 3): return (new Fraction(-1, 3), MathS.Sqrt(3), 3); + case (1, 6): return (Fraction.One, MathS.Sqrt(3), 3); + case (5, 6): return (Fraction.MinusOne, MathS.Sqrt(3), 3); + default: return (Fraction.One, MathS.Cotan(MathS.pi * x.Entity), 0); + } + } + + // cos 2πt as a fraction, or times the cosine itself + private static (Fraction Value, Entity? Irrational) Cosine(Fraction t) + { + t -= t.Floor(); + switch ((int)t.Numerator, (int)t.Denominator) + { + case (0, 1): return (Fraction.One, null); + case (1, 2): return (Fraction.MinusOne, null); + case (1, 4) or (3, 4): return (Fraction.Zero, null); + case (1, 3) or (2, 3): return (new Fraction(-1, 2), null); + case (1, 6) or (5, 6): return (Half, null); + default: return (Fraction.One, MathS.Cos(2 * MathS.pi * t.Entity)); + } + } + + // ln sin πt for 0 < t < 1, as fractions times logarithms + private static (Fraction Coefficient, Entity Logarithm)[] LogSine(Fraction t) + { + switch ((int)t.Numerator, (int)t.Denominator) + { + case (1, 2): return Array.Empty<(Fraction, Entity)>(); + case (1, 6) or (5, 6): return new[] { (Fraction.MinusOne, MathS.Ln(2)) }; + case (1, 4) or (3, 4): return new[] { (new Fraction(-1, 2), MathS.Ln(2)) }; + case (1, 3) or (2, 3): return new[] { (Half, MathS.Ln(3)), (Fraction.MinusOne, MathS.Ln(2)) }; + default: return new[] { (Fraction.One, MathS.Ln(MathS.Sin(MathS.pi * t.Entity))) }; + } + } + + // dᵐ/dxᵐ cot πx = πᵐ Pₘ(cot πx): P₀ = c, Pₘ₊₁ = −(1 + c²) Pₘ′ + private static BigInteger[] CotangentDerivative(int order) + { + var p = new[] { BigInteger.Zero, BigInteger.One }; + for (var m = 0; m < order; m++) + { + var next = new BigInteger[p.Length + 1]; + for (var i = 1; i < p.Length; i++) + { + next[i - 1] -= i * p[i]; + next[i + 1] -= i * p[i]; + } + p = next; + } + return p; + } + + // ζ(p)/πᵖ for an even p: (−1)^(p/2+1) Bₚ 2ᵖ / (2 p!) + private static Fraction ZetaOfEven(int p) => + Bernoulli(p) * new Fraction((p / 2 % 2 == 1 ? 1 : -1) * BigInteger.Pow(2, p), 2 * Factorial(p)); + + // Bₙ, by the algorithm of Akiyama and Tanigawa + private static Fraction Bernoulli(int n) + { + var a = new Fraction[n + 1]; + for (var m = 0; m <= n; m++) + { + a[m] = new Fraction(1, m + 1); + for (var j = m; j >= 1; j--) + a[j - 1] = j * (a[j - 1] - a[j]); + } + return a[0]; + } + + private static BigInteger Factorial(int n) + { + BigInteger f = 1; + for (var i = 2; i <= n; i++) + f *= i; + return f; + } + + // the partial fractions c/(k − root)ʲ and β/(k² + bk + c) of a term + private sealed class Parts + { + public List<(Fraction C, Fraction Root, int Power)> Poles { get; } = new List<(Fraction, Fraction, int)>(); + + public List<(Fraction Beta, Fraction B, Fraction C)> Quadratics { get; } = new List<(Fraction, Fraction, Fraction)>(); + } + + // a fraction plus fractions times numbers that are not (π², ln 2, π√3…), those of one number added together + private sealed class Combination + { + private readonly Dictionary numbers = new Dictionary(); + + private readonly List order = new List(); + + private Fraction fraction = Fraction.Zero; + + /// How many times the constant of Euler, which no value in closed form has. + public Fraction Gamma { get; set; } = Fraction.Zero; + + public void Add(Fraction coefficient, params Entity?[] factors) + { + Entity? number = null; + foreach (var factor in factors) + if (factor is not null) + number = number is null ? factor : number * factor; + if (number is null) + { + fraction += coefficient; + return; + } + var key = number.ToString(); + if (numbers.TryGetValue(key, out var known)) + { + numbers[key] = (known.Coefficient + coefficient, known.Number); + return; + } + numbers[key] = (coefficient, number); + order.Add(key); + } + + public Entity? Value() + { + if (!Gamma.IsZero) + return null; + Entity? sum = null; + foreach (var key in order) + { + var (coefficient, number) = numbers[key]; + if (coefficient.IsZero) + continue; + var term = coefficient == Fraction.One ? number : coefficient.Entity * number; + sum = sum is null ? term : sum + term; + } + if (sum is null || !fraction.IsZero) + sum = sum is null ? fraction.Entity : sum + fraction.Entity; + return sum; + } + } + } +} diff --git a/samples/SharpEquations.MathTools.Core/Cas/SeriesAlgebra.cs b/samples/SharpEquations.MathTools.Core/Cas/SeriesAlgebra.cs new file mode 100644 index 0000000..ecbd206 --- /dev/null +++ b/samples/SharpEquations.MathTools.Core/Cas/SeriesAlgebra.cs @@ -0,0 +1,288 @@ +namespace SharpEquations.MathTools +{ + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Numerics; + using AngouriMath; + + /// An exact fraction of whole numbers, in lowest terms with a positive denominator. + internal readonly struct Fraction : IEquatable + { + public static readonly Fraction Zero = new Fraction(0, 1); + + public static readonly Fraction One = new Fraction(1, 1); + + public static readonly Fraction MinusOne = new Fraction(-1, 1); + + private readonly BigInteger denominator; + + public Fraction(BigInteger numerator, BigInteger denominator) + { + if (denominator.IsZero) + throw new DivideByZeroException(); + if (denominator.Sign < 0) + { + numerator = -numerator; + denominator = -denominator; + } + var gcd = BigInteger.GreatestCommonDivisor(numerator, denominator); + Numerator = numerator / gcd; + this.denominator = denominator / gcd; + } + + public BigInteger Numerator { get; } + + public BigInteger Denominator => denominator.IsZero ? BigInteger.One : denominator; + + public bool IsZero => Numerator.IsZero; + + public bool IsInteger => Denominator.IsOne; + + public int Sign => Numerator.Sign; + + /// The fraction as a number of AngouriMath. + public Entity Entity => MathS.FromString( + IsInteger + ? "(" + Numerator.ToString(CultureInfo.InvariantCulture) + ")" + : "(" + Numerator.ToString(CultureInfo.InvariantCulture) + "/" + Denominator.ToString(CultureInfo.InvariantCulture) + ")", + useCache: false); + + public static implicit operator Fraction(long value) => new Fraction(value, 1); + + public static implicit operator Fraction(BigInteger value) => new Fraction(value, 1); + + public static Fraction operator +(Fraction x, Fraction y) => + new Fraction(x.Numerator * y.Denominator + y.Numerator * x.Denominator, x.Denominator * y.Denominator); + + public static Fraction operator -(Fraction x, Fraction y) => + new Fraction(x.Numerator * y.Denominator - y.Numerator * x.Denominator, x.Denominator * y.Denominator); + + public static Fraction operator -(Fraction x) => new Fraction(-x.Numerator, x.Denominator); + + public static Fraction operator *(Fraction x, Fraction y) => new Fraction(x.Numerator * y.Numerator, x.Denominator * y.Denominator); + + public static Fraction operator /(Fraction x, Fraction y) => new Fraction(x.Numerator * y.Denominator, x.Denominator * y.Numerator); + + public static bool operator ==(Fraction x, Fraction y) => x.Equals(y); + + public static bool operator !=(Fraction x, Fraction y) => !x.Equals(y); + + public static bool operator <(Fraction x, Fraction y) => (x - y).Sign < 0; + + public static bool operator >(Fraction x, Fraction y) => (x - y).Sign > 0; + + public static bool operator <=(Fraction x, Fraction y) => (x - y).Sign <= 0; + + public static bool operator >=(Fraction x, Fraction y) => (x - y).Sign >= 0; + + /// The fraction to a whole power, which may be negative. + public Fraction Pow(int exponent) => exponent >= 0 + ? new Fraction(BigInteger.Pow(Numerator, exponent), BigInteger.Pow(Denominator, exponent)) + : new Fraction(BigInteger.Pow(Denominator, -exponent), BigInteger.Pow(Numerator, -exponent)); + + /// The greatest whole number not above the fraction. + public BigInteger Floor() + { + var quotient = BigInteger.DivRem(Numerator, Denominator, out var remainder); + return remainder.Sign < 0 ? quotient - 1 : quotient; + } + + /// The fraction whose square this is, or null. + public Fraction? SquareRoot() + { + if (Sign < 0) + return null; + var n = Root(Numerator); + var d = Root(Denominator); + return n * n == Numerator && d * d == Denominator ? new Fraction(n, d) : (Fraction?)null; + } + + public bool Equals(Fraction other) => Numerator == other.Numerator && Denominator == other.Denominator; + + public override bool Equals(object? obj) => obj is Fraction other && Equals(other); + + public override int GetHashCode() => Numerator.GetHashCode() ^ (Denominator.GetHashCode() * 397); + + public override string ToString() => IsInteger ? Numerator.ToString(CultureInfo.InvariantCulture) : Numerator.ToString(CultureInfo.InvariantCulture) + "/" + Denominator.ToString(CultureInfo.InvariantCulture); + + // the whole part of the square root, by Newton's method + private static BigInteger Root(BigInteger n) + { + if (n < 2) + return n; + var x = (BigInteger)Math.Sqrt((double)n); + while (x * x > n) + x--; + while ((x + 1) * (x + 1) <= n) + x++; + return x; + } + } + + /// A polynomial of one letter with fractions as coefficients, from the constant one up. + internal sealed class Polynomial + { + public static readonly Polynomial Zero = new Polynomial(Array.Empty()); + + public static readonly Polynomial One = Constant(Fraction.One); + + public static readonly Polynomial X = new Polynomial(new[] { Fraction.Zero, Fraction.One }); + + private readonly Fraction[] coefficients; + + public Polynomial(IReadOnlyList coefficients) + { + var length = coefficients.Count; + while (length > 0 && coefficients[length - 1].IsZero) + length--; + this.coefficients = new Fraction[length]; + for (var i = 0; i < length; i++) + this.coefficients[i] = coefficients[i]; + } + + /// The degree, −1 for the polynomial zero. + public int Degree => coefficients.Length - 1; + + public bool IsZero => coefficients.Length == 0; + + public Fraction Leading => IsZero ? Fraction.Zero : coefficients[coefficients.Length - 1]; + + public Fraction this[int power] => power < coefficients.Length ? coefficients[power] : Fraction.Zero; + + public static Polynomial Constant(Fraction value) => new Polynomial(new[] { value }); + + /// x − root. + public static Polynomial Linear(Fraction root) => new Polynomial(new[] { -root, Fraction.One }); + + public static Polynomial operator +(Polynomial x, Polynomial y) + { + var sum = new Fraction[Math.Max(x.coefficients.Length, y.coefficients.Length)]; + for (var i = 0; i < sum.Length; i++) + sum[i] = x[i] + y[i]; + return new Polynomial(sum); + } + + public static Polynomial operator -(Polynomial x, Polynomial y) => x + y * Fraction.MinusOne; + + public static Polynomial operator *(Polynomial x, Fraction y) + { + var product = new Fraction[x.coefficients.Length]; + for (var i = 0; i < product.Length; i++) + product[i] = x.coefficients[i] * y; + return new Polynomial(product); + } + + public static Polynomial operator *(Polynomial x, Polynomial y) + { + if (x.IsZero || y.IsZero) + return Zero; + var product = new Fraction[x.coefficients.Length + y.coefficients.Length - 1]; + for (var i = 0; i < product.Length; i++) + product[i] = Fraction.Zero; + for (var i = 0; i < x.coefficients.Length; i++) + for (var j = 0; j < y.coefficients.Length; j++) + product[i + j] += x.coefficients[i] * y.coefficients[j]; + return new Polynomial(product); + } + + /// The quotient and the remainder of a division by a polynomial that is not zero. + public (Polynomial Quotient, Polynomial Remainder) DivRem(Polynomial divisor) + { + if (divisor.IsZero) + throw new DivideByZeroException(); + var remainder = (Fraction[])coefficients.Clone(); + var quotient = new Fraction[Math.Max(0, Degree - divisor.Degree + 1)]; + for (var i = 0; i < quotient.Length; i++) + quotient[i] = Fraction.Zero; + for (var power = Degree; power >= divisor.Degree; power--) + { + var factor = remainder[power] / divisor.Leading; + quotient[power - divisor.Degree] = factor; + for (var i = 0; i <= divisor.Degree; i++) + remainder[power - divisor.Degree + i] -= factor * divisor[i]; + } + return (new Polynomial(quotient), new Polynomial(remainder)); + } + + /// The greatest common divisor, with 1 as its first coefficient. + public static Polynomial Gcd(Polynomial x, Polynomial y) + { + while (!y.IsZero) + (x, y) = (y, x.DivRem(y).Remainder); + return x.IsZero ? x : x * (Fraction.One / x.Leading); + } + + public Fraction Evaluate(Fraction at) + { + var value = Fraction.Zero; + for (var i = coefficients.Length - 1; i >= 0; i--) + value = value * at + coefficients[i]; + return value; + } + + /// The polynomial of scale·x + shift. + public Polynomial Compose(Fraction scale, Fraction shift) + { + var inner = new Polynomial(new[] { shift, scale }); + var result = Zero; + for (var i = coefficients.Length - 1; i >= 0; i--) + result = result * inner + Constant(coefficients[i]); + return result; + } + + public Polynomial Pow(int exponent) + { + var result = One; + for (var i = 0; i < exponent; i++) + result *= this; + return result; + } + } + + /// A quotient of polynomials in lowest terms, the first coefficient of the denominator 1. + internal sealed class RationalFunction + { + public static readonly RationalFunction Zero = new RationalFunction(Polynomial.Zero, Polynomial.One); + + public RationalFunction(Polynomial numerator, Polynomial denominator) + { + if (denominator.IsZero) + throw new DivideByZeroException(); + var gcd = Polynomial.Gcd(numerator, denominator); + var scale = Fraction.One / denominator.Leading; + Numerator = numerator.DivRem(gcd).Quotient * (scale * gcd.Leading); + Denominator = denominator.DivRem(gcd).Quotient * (scale * gcd.Leading); + var leading = Fraction.One / Denominator.Leading; + Numerator *= leading; + Denominator *= leading; + } + + public Polynomial Numerator { get; } + + public Polynomial Denominator { get; } + + public bool IsZero => Numerator.IsZero; + + /// How much faster the denominator grows: the degree of the one less that of the other. + public int Gap => Denominator.Degree - Numerator.Degree; + + public static RationalFunction operator +(RationalFunction x, RationalFunction y) => + new RationalFunction(x.Numerator * y.Denominator + y.Numerator * x.Denominator, x.Denominator * y.Denominator); + + public static RationalFunction operator -(RationalFunction x) => new RationalFunction(x.Numerator * Fraction.MinusOne, x.Denominator); + + public static RationalFunction operator -(RationalFunction x, RationalFunction y) => x + -y; + + public static RationalFunction operator *(RationalFunction x, RationalFunction y) => + new RationalFunction(x.Numerator * y.Numerator, x.Denominator * y.Denominator); + + /// The quotient by a function that is not zero. + public static RationalFunction operator /(RationalFunction x, RationalFunction y) => + new RationalFunction(x.Numerator * y.Denominator, x.Denominator * y.Numerator); + + /// The function of scale·x + shift. + public RationalFunction Compose(Fraction scale, Fraction shift) => + new RationalFunction(Numerator.Compose(scale, shift), Denominator.Compose(scale, shift)); + } +} diff --git a/samples/SharpEquations.MathTools.MathEngine/MathEngineN.cs b/samples/SharpEquations.MathTools.MathEngine/MathEngineN.cs new file mode 100644 index 0000000..4b5592c --- /dev/null +++ b/samples/SharpEquations.MathTools.MathEngine/MathEngineN.cs @@ -0,0 +1,475 @@ +namespace SharpEquations.MathTools.MathEngine +{ + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Collections.Concurrent; + using System.Runtime.InteropServices; + using System.Threading; + using System.Threading.Tasks; + using AngouriMath; + using SharpEquations; + using SharpEquations.MathTools; + + /// + /// The engine of Microsoft Mathematics (mathenginen.dll) as an , to compare its results with + /// those of . The equation is read by (the letters defined + /// replaced by their values), written in the linear input of the engine, and the result comes back as MathML. + /// It needs Windows and an installation of Microsoft Mathematics of the same processor as the process; the + /// library is never part of this repository (see ). + /// + public sealed class MathEngineN : ICasEngine, IDisposable + { + private const int Formula = 0; + private const int Linear = 2; + private const int MathML = 4; + private const int SolveEquation = 0; + private const int NonEquation = 2; + + // the error -8 of a request, what the engine answers for a system with no solution + private const int NoSolution = 17; + + private static readonly Guid Key = new Guid("15D1265B-8A3C-413a-BF1E-38CC9285C186"); + private static readonly object Loading = new object(); + private static IntPtr handle; + private static bool? available; + + private readonly object gate = new object(); + private readonly Dictionary definitions = new Dictionary(StringComparer.Ordinal); + private Guid context; + + /// The library is not there (). + public MathEngineN() + { + if (!IsAvailable) + throw new PlatformNotSupportedException("The engine of Microsoft Mathematics is not installed (mathenginen.dll)."); + context = OnEngineThread(() => + { + Check(NativeMethods.CreateContext(Key, out var created)); + return created; + }); + } + + /// + /// Where the library is looked for: the environment variable MATHENGINEN_PATH, else the folder of + /// Microsoft Mathematics in the program files; null when it is in neither. + /// + public static string? LibraryPath + { + get + { + if (Environment.GetEnvironmentVariable("MATHENGINEN_PATH") is { Length: > 0 } path) + return File.Exists(path) ? path : null; + foreach (var folder in new[] { Environment.SpecialFolder.ProgramFiles, Environment.SpecialFolder.ProgramFilesX86 }) + { + var file = Path.Combine(Environment.GetFolderPath(folder), "Microsoft Mathematics", NativeMethods.Library); + if (File.Exists(file)) + return file; + } + return null; + } + } + + /// Whether the engine can be used: on Windows, with the library of the processor of the process, loaded. + public static bool IsAvailable + { + get + { + lock (Loading) + return available ??= Load(); + } + } + + public string Name => "Microsoft Mathematics"; + + public AngleUnit Angles { get; set; } + + /// Whether equations are solved among the complex numbers (true, the default) or the real ones. + public bool Complex { get; set; } = true; + + public IReadOnlyDictionary Definitions + { + get + { + lock (gate) + return definitions.ToDictionary(d => d.Key, d => AngouriMathEngine.ToEquation(d.Value) ?? Equation.Parse(d.Value.ToString(), EquationFormat.UnicodeMath)); + } + } + + public void ClearDefinitions() + { + lock (gate) + definitions.Clear(); + } + + public IReadOnlyList Variables(Equation equation) + { + if (MathReader.TryReadDefinition(equation, AngleUnit.Radians, out _, out var value)) + return AngouriMathEngine.Variables(Substitute(value)); + return AngouriMathEngine.Variables(MathReader.ReadSystem(equation, AngleUnit.Radians).Select(Substitute).ToArray()); + } + + public CasResult Run(CasAction action, Equation equation, string? variable = null) + { + // read in the unit of angles (30° and the trigonometric functions become radians): the engine computes in radians + List system; + if (MathReader.TryReadDefinition(equation, Angles, out var name, out var value)) + { + value = Substitute(value); + if (action == CasAction.Define) + { + if (value.Vars.Any(v => v.Name == name)) + throw new NotSupportedException("“" + name + "” cannot be defined by itself."); + lock (gate) + definitions[name] = value; + var values = AngouriMathEngine.ToEquation(value) is { } defined ? new[] { defined } : Array.Empty(); + return new CasResult(CasAction.Define, null, name + " ≔ " + value.ToString()) { Values = values }; + } + system = new List { value }; + } + else if (action == CasAction.Define) + { + throw new NotSupportedException("A definition is a letter, ≔ and its value: a≔5."); + } + else + { + system = MathReader.ReadSystem(equation, Angles).Select(Substitute).ToList(); + } + + var letters = AngouriMathEngine.Variables(system.ToArray()); + var x = variable ?? (letters.Count > 0 ? letters[0] : null); + lock (gate) + { + ObjectDisposedException.ThrowIf(context == Guid.Empty, this); + if (action == CasAction.Solve) + { + // the engine solves for its own first letter: the one asked for takes its place, and back + var swap = variable != null && system.Count == 1 && letters.Count > 1 && letters[0] != variable + ? new[] { MathReader.Symbol(variable), MathReader.Symbol(letters[0]) } + : null; + if (swap != null) + system = system.Select(e => Swapped(e, variable!, letters[0])).ToList(); + var equations = MathEngineText.Equations(system); + var unknowns = swap != null ? new[] { letters[0] } : system.Count > 1 ? letters : x != null ? new[] { x } : letters; + var named = variable != null && system.Count == 1; + return OnEngineThread(() => Solve(equations, unknowns, named, swap)); + } + var command = MathEngineText.Command(action, system, x); + var imaginary = system.Any(e => e.Nodes.Any(n => n is Entity.Number.Complex c && c.ImaginaryPart != 0)); + return OnEngineThread(() => Execute(action, command, imaginary)); + } + } + + // as Microsoft Mathematics does: each equation read in the linear format and written as a formula, all of them + // in SymbolicSolve[List[…]], read as a formula and solved through a request, which takes the letters to solve for + // among the complex numbers, else among the real ones when that fails (|x-1|=3) or gives a family of values + // with a parameter (eˣ=5) or in polar form (y²=25-x²); the letter asked for even when the request does not ask, else without it + private CasResult Solve(IReadOnlyList equations, IReadOnlyList unknowns, bool named, string[]? swap) + { + if (!Complex) + return Attempt(equations, unknowns, named, false, swap); + + CasResult complex; + try + { + complex = Attempt(equations, unknowns, named, true, swap); + } + catch (InvalidOperationException) + { + return Attempt(equations, unknowns, named, false, swap); + } + + if (!complex.Text.Contains("𝒩", StringComparison.Ordinal) && !complex.Text.Contains("arg(", StringComparison.Ordinal) && complex.Values.Count > 0) + return complex; + try + { + var real = Attempt(equations, unknowns, named, false, swap); + return real.Values.Count > 0 ? real : complex; + } + catch (InvalidOperationException) + { + return complex; + } + } + + private CasResult Attempt(IReadOnlyList equations, IReadOnlyList unknowns, bool named, bool complex, string[]? swap) + { + if (!named) + return Request(equations, unknowns, false, complex, swap); + try + { + return Request(equations, unknowns, true, complex, swap); + } + catch (SEHException) + { + return Request(equations, unknowns, false, complex, swap); + } + } + + private CasResult Request(IReadOnlyList equations, IReadOnlyList unknowns, bool named, bool complex, string[]? swap) + { + var created = new List(); + try + { + var formulas = new List(); + foreach (var equation in equations) + { + var one = Parse(equation, Linear, SolveEquation, complex); + created.Add(one); + formulas.Add(Serialize(one, Formula)); + } + var command = MathEngineText.SolveCommand(formulas); + var parsed = Parse(command, Formula, SolveEquation, complex); + created.Add(parsed); + Check(NativeMethods.CreateEquationRequest(context, parsed, out var request)); + created.Add(request); + // as Microsoft Mathematics: the letters only when the request asks for them, else the engine fails + // (or when the letter is asked for, which can fail) + var required = NativeMethods.EquationRequestRequireVariableList(context, request, out var asks) == 0 && asks; + if ((required || named) && unknowns.Count > 0) + Check(NativeMethods.EquationRequestSetVarNames(context, request, string.Join(",", unknowns.Select(MathReader.Symbol)))); + + SetEvaluation(complex); + var code = NativeMethods.ExecuteExpression(context, request, out var result); + if (code == NoSolution) + return new CasResult(CasAction.Solve, null, "") { Values = Array.Empty() }; + Check(code); + created.Add(result); + return Result(CasAction.Solve, result, swap); + } + finally + { + foreach (var expression in created.Distinct()) + NativeMethods.DestroyExpression(context, expression); + } + } + + // among the real numbers (∛(-8) is -2), else among the complex ones when the input has i or the real result + // is indeterminate (√(-4) is 2i) + private CasResult Execute(CasAction action, string command, bool imaginary) + { + if (!imaginary) + { + var real = Execute(action, command, false, out var indeterminate); + if (!indeterminate) + return real; + } + return Execute(action, command, true, out _); + } + + private CasResult Execute(CasAction action, string command, bool complex, out bool indeterminate) + { + var created = new List(); + try + { + var parsed = Parse(command, Linear, NonEquation, complex); + created.Add(parsed); + SetEvaluation(complex); + Check(NativeMethods.ExecuteExpression(context, parsed, out var result)); + created.Add(result); + if (action == CasAction.Simplify) + { + // as Microsoft Mathematics simplifies: the evaluated expression, then all of its simplifications + Check(NativeMethods.FullSimplifyExpression(context, result, out result)); + created.Add(result); + } + var answer = Result(action, result); + if (action == CasAction.Simplify) + answer = Contracted(answer); + indeterminate = answer.Text.Contains("Indeterminate", StringComparison.Ordinal); + return answer; + } + finally + { + foreach (var expression in created.Distinct()) + NativeMethods.DestroyExpression(context, expression); + } + } + + // the input is in radians (see Run): so is the engine + private void SetEvaluation(bool complex) => + Check(NativeMethods.SetEvaluationProperties(context, complex ? 1 : 0, 0, false, false, false, true)); + + private int Parse(string text, int format, int mode, bool complex) + { + Check(NativeMethods.SetParsingOptions(context, format, true, true, true, mode)); + SetEvaluation(complex); + var code = NativeMethods.Parse(context, text, out var parsed); + if (code == 0) + return parsed; + var where = NativeMethods.GetParsingErrorRange(context, out var start, out var length) == 0 && start >= 0 && start < text.Length + ? " at “" + text.Substring(start, Math.Clamp(length, 1, text.Length - start)) + "”" + : ""; + throw new NotSupportedException(MathEngineText.Error(code) + where + ": " + text); + } + + private static Entity Swapped(Entity e, string a, string b) + { + var spare = MathS.Var("swapped" + a + b); + return e.Substitute(MathS.Var(a), spare).Substitute(MathS.Var(b), MathS.Var(a)).Substitute(spare, MathS.Var(b)); + } + + // the engine has no command that writes sin x cos x as a sine of 2x + private static CasResult Contracted(CasResult answer) + { + IReadOnlyList read; + try + { + read = MathEngineText.ReadLinear(answer.Text); + } + catch (FormatException) + { + return answer; + } + + if (read.Count != 1 || MathEngineText.Contracted(read[0]) is not { } contracted || ReferenceEquals(contracted, read[0])) + return answer; + return AngouriMathEngine.ToEquation(contracted) is { } math + ? new CasResult(answer.Action, math, contracted.ToString()) { Values = new[] { math } } + : answer; + } + + // the values of a result: from its linear text, read by AngouriMath, else from its MathML + private CasResult Result(CasAction action, int result, string[]? swap = null) + { + var mathML = MathEngineText.DecodeEntities(Serialize(result, MathML)); + var text = Serialize(result, Linear); + if (swap != null) + (text, mathML) = (MathEngineText.Swapped(text, swap[0], swap[1]), MathEngineText.SwappedMathML(mathML, swap[0], swap[1])); + var display = new EquationOptions { Display = true }; + var math = Equation.TryParse(mathML, EquationFormat.MathML, display, out var parsedResult) ? parsedResult : null; + + var values = new List(); + try + { + foreach (var value in MathEngineText.ReadLinear(text)) + { + if (AngouriMathEngine.ToEquation(value) is not { } one) + { + values.Clear(); + break; + } + values.Add(one); + } + } + catch (FormatException) + { + values.Clear(); + } + if (values.Count == 0) + { + foreach (var piece in MathEngineText.Values(mathML)) + { + if (!Equation.TryParse(piece.ToString(), EquationFormat.MathML, display, out var one)) + { + values.Clear(); + break; + } + values.Add(one); + } + } + if (action != CasAction.Solve && values.Count > 1) + values.RemoveRange(1, values.Count - 1); + return new CasResult(action, math, text) { Values = values }; + } + + private string Serialize(int expression, int format) + { + Check(NativeMethods.SetFormatingOptions(context, format, 13, 1e12, 1e-4, "", false, 1)); + Check(NativeMethods.Serialize(context, expression, out var text)); + return text; + } + + private Entity Substitute(Entity expression) + { + lock (gate) + { + for (var round = 0; round < 8 && expression.Vars.Any(v => definitions.ContainsKey(v.Name)); round++) + foreach (var letter in expression.Vars.Where(v => definitions.ContainsKey(v.Name)).ToList()) + expression = expression.Substitute(letter, definitions[letter.Name]); + } + return expression; + } + + public void Dispose() + { + lock (gate) + { + if (context == Guid.Empty) + return; + var destroyed = context; + context = Guid.Empty; + OnEngineThread(() => NativeMethods.DestroyContext(destroyed)); + } + } + + /// + /// Runs a call of the library on its own thread. The library keeps every context in one table, not guarded + /// against threads, keeps state per thread and initializes COM on the thread that calls it, as on the one + /// thread (single-threaded apartment) of Microsoft Mathematics: so all the calls, of every engine, go to one + /// such thread, one at a time. + /// + private static T OnEngineThread(Func call) + { + var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + Calls.Value.Add(() => + { + try + { + done.SetResult(call()); + } +#pragma warning disable CA1031 // every failure goes back to the caller + catch (Exception exception) +#pragma warning restore CA1031 + { + done.SetException(exception); + } + }); + return done.Task.GetAwaiter().GetResult(); + } + + private static readonly Lazy> Calls = new Lazy>(() => + { + var calls = new BlockingCollection(); + var thread = new Thread(() => + { + foreach (var call in calls.GetConsumingEnumerable()) + call(); + }) + { + IsBackground = true, + Name = "Microsoft Mathematics engine", + }; + if (OperatingSystem.IsWindows()) + thread.SetApartmentState(ApartmentState.STA); + thread.Start(); + return calls; + }); + + private static void Check(int code) + { + if (MathEngineText.Error(code) is { } error) + throw new InvalidOperationException(error); + } + + private static bool Load() + { + if (!OperatingSystem.IsWindows() || LibraryPath is not { } path) + return false; + ushort? machine; + using (var file = File.OpenRead(path)) + machine = MathEngineText.Machine(file); + var expected = RuntimeInformation.ProcessArchitecture switch + { + Architecture.X64 => (ushort)0x8664, + Architecture.X86 => (ushort)0x14C, + _ => (ushort)0, + }; + if (machine != expected || !NativeLibrary.TryLoad(path, out handle)) + return false; + NativeLibrary.SetDllImportResolver(typeof(MathEngineN).Assembly, (name, _, _) => name == NativeMethods.Library ? handle : IntPtr.Zero); + return true; + } + } +} diff --git a/samples/SharpEquations.MathTools.MathEngine/MathEngineText.cs b/samples/SharpEquations.MathTools.MathEngine/MathEngineText.cs new file mode 100644 index 0000000..5423c26 --- /dev/null +++ b/samples/SharpEquations.MathTools.MathEngine/MathEngineText.cs @@ -0,0 +1,500 @@ +namespace SharpEquations.MathTools.MathEngine +{ + using System; + using System.Collections.Generic; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Text; + using System.Text.RegularExpressions; + using System.Xml.Linq; + using AngouriMath; + using MathNet.Symbolics; + using SharpEquations.MathTools; + + /// + /// What the adapter of mathenginen.dll writes and reads, without the library (so that it is tested everywhere): the + /// linear input of an expression, the command of an action, the meaning of an error code, the values of a result + /// and the processor a library is built for. + /// + public static class MathEngineText + { + /// The linear input of an expression of AngouriMath: sin(x)^2+(1/2)*x. + /// Something the engine has no input for. + public static string Linear(Entity value) => value switch + { + Entity.Number.Integer n => n.EInteger.ToString(), + Entity.Number.Rational q => "(" + q.ERational.Numerator.ToString() + "/" + q.ERational.Denominator.ToString() + ")", + Entity.Number.Real r => Real(r), + Entity.Number.Complex c => "(" + Real(c.RealPart) + "+" + Real(c.ImaginaryPart) + "*i)", + Entity.Variable v when v == MathS.pi => "pi", + Entity.Variable v when v == MathS.e => "e", + Entity.Variable v => MathReader.Symbol(v.Name), + Entity.Sumf(var a, var b) when Linear(b) is var right && right.StartsWith('-') => Child(a, 1) + right, + Entity.Sumf(var a, var b) => Child(a, 1) + "+" + Child(b, 1), + Entity.Minusf(var a, var b) => Child(a, 1) + "-" + Child(b, 2), + Entity.Mulf(Entity.Number.Integer n, var b) when n.EInteger.IsZero == false && n.EInteger.Sign < 0 => + n.EInteger.Abs().Equals(PeterO.Numbers.EInteger.One) ? "-" + Child(b, 2) : "-" + n.EInteger.Abs().ToString() + "*" + Child(b, 2), + Entity.Mulf(var a, var b) => Child(a, 2) + "*" + Child(b, 2), + Entity.Divf(var a, var b) => Child(a, 2) + "/" + Child(b, 3), + Entity.Powf(var a, var b) => Child(a, 4) + "^" + Child(b, 4), + Entity.Sinf(var a) => Call("sin", a), + Entity.Cosf(var a) => Call("cos", a), + Entity.Tanf(var a) => Call("tan", a), + Entity.Cotanf(var a) => Call("cot", a), + Entity.Secantf(var a) => Call("sec", a), + Entity.Cosecantf(var a) => Call("csc", a), + Entity.Arcsinf(var a) => Call("arcsin", a), + Entity.Arccosf(var a) => Call("arccos", a), + Entity.Arctanf(var a) => Call("arctan", a), + Entity.Arccotanf(var a) => Call("arccot", a), + Entity.Arcsecantf(var a) => Call("arcsec", a), + Entity.Arccosecantf(var a) => Call("arccsc", a), + Entity.Logf(var b, var x) when b == MathS.e => Call("ln", x), + Entity.Logf(var b, var x) => Call("ln", x) + "/" + Call("ln", b), + Entity.Absf(var a) => Call("abs", a), + Entity.Factorialf(var a) => Child(a, 4) + "!", + Entity.Signumf(var a) => Call("sign", a), + Entity.Floorf(var a) => Call("floor", a), + Entity.Ceilf(var a) => Call("ceiling", a), + Entity.Binomialf(var n, var k) => "combination(" + Linear(n) + "," + Linear(k) + ")", + Entity.Integralf(var f, var x, var range) when range is var (from, to) => + "integral(" + Linear(f) + "," + Linear(x) + "," + Linear(from) + "," + Linear(to) + ")", + Entity.Summationf(var f, var k, var from, var to) => "seriesSum(" + Linear(f) + "," + Linear(k) + "," + Linear(from) + "," + Linear(to) + ")", + Entity.Productf(var f, var k, var from, var to) => "seriesProduct(" + Linear(f) + "," + Linear(k) + "," + Linear(from) + "," + Linear(to) + ")", + Entity.Equalsf(var a, var b) => Linear(a) + "=" + Linear(b), + _ => throw new NotSupportedException("The engine of Microsoft Mathematics has no input for “" + value.ToString() + "”."), + }; + + private static string Real(Entity.Number.Real r) => + r.IsFinite ? r.EDecimal.ToDouble().ToString("R", CultureInfo.InvariantCulture) : r.EDecimal.IsNegative ? "-∞" : "∞"; + + private static string Call(string name, Entity argument) => name + "(" + Linear(argument) + ")"; + + // a child in brackets when it binds less than its place needs: 1 sums, 2 products, 3 powers, 4 the rest + private static string Child(Entity value, int needed) + { + var text = Linear(value); + return Binding(value, text) < needed ? "(" + text + ")" : text; + } + + private static int Binding(Entity value, string text) => value switch + { + Entity.Sumf or Entity.Minusf => 1, + Entity.Mulf or Entity.Divf => 2, + Entity.Powf => 3, + Entity.Equalsf => 0, + _ when text.StartsWith('-') => 1, + _ => 4, + }; + + /// + /// The input of an action on a system of equations (or a single expression): the equation itself for + /// (an expression is set equal to 0, the equations of a system are separated by + /// commas) and for , a function of the engine for the others. + /// + public static string Command(CasAction action, IReadOnlyList system, string? variable) + { + if (system.Count == 0) + throw new ArgumentException("No equation.", nameof(system)); + if (action == CasAction.Solve) + return string.Join(", ", Equations(system)); + if (system.Count > 1) + throw new NotSupportedException("A system of equations: it can only be solved."); + var expression = Linear(system[0]); + var x = variable != null ? MathReader.Symbol(variable) : null; + return action switch + { + CasAction.Evaluate => expression, + CasAction.Simplify => expression, + CasAction.Expand => "expand(" + expression + ")", + CasAction.Factor => "factor(" + expression + ")", + CasAction.Differentiate => "deriv(" + expression + "," + (x ?? "x") + ")", + CasAction.Integrate => "integral(" + expression + "," + (x ?? "x") + ")", + _ => throw new NotSupportedException("The engine of Microsoft Mathematics does not do “" + action + "”."), + }; + } + + /// The linear input of each equation of a system to solve: an expression is set equal to 0. + public static IReadOnlyList Equations(IReadOnlyList system) => + system.Select(e => e is Entity.Equalsf ? Linear(e) : Linear(e) + "=0").ToList(); + + /// + /// The command that solves equations in the format of formulas of the engine (as Microsoft Mathematics asks + /// for a solution): SymbolicSolve[List[…]]. + /// + public static string SolveCommand(IEnumerable formulas) => "SymbolicSolve[List[" + string.Join(",", formulas) + "]]"; + + /// What an error code of the engine means, or null for 0. + public static string? Error(int code) + { + if (code == 0) + return null; + var kind = (code >> 16) & 0xFFFF; + var low = code & 0xFFFF; + var number = low % 2 == 1 ? -(low / 2) : low / 2; + return kind switch + { + 2 => "The computation was stopped.", + 1 => "The engine of Microsoft Mathematics cannot read this (error " + number.ToString(CultureInfo.InvariantCulture) + ").", + _ => "The engine of Microsoft Mathematics cannot compute this (error " + number.ToString(CultureInfo.InvariantCulture) + ").", + }; + } + + /// + /// The values of a result in MathML, one math element each: the pieces of its row between commas, + /// semicolons and “or”, each the right side of its last =, without what follows ≈. + /// + public static IReadOnlyList Values(string mathML) + { + var root = XElement.Parse(DecodeEntities(mathML)); + XNamespace ns = root.Name.Namespace; + var row = root; + while (row.Elements().Count() == 1 && row.Elements().Single().Name.LocalName is "mrow" or "mstyle" or "semantics") + row = row.Elements().Single(); + if (row.Name.LocalName == "semantics") + row = row.Elements().First(); + + var values = new List(); + var piece = new List(); + foreach (var item in row.Elements().Where(e => e.Name.LocalName is not ("annotation" or "annotation-xml"))) + { + if (IsSeparator(item)) + { + Add(); + continue; + } + piece.Add(item); + } + Add(); + return values; + + void Add() + { + if (IsNotValue(string.Concat(piece.Select(e => e.Value)))) + { + piece = new List(); + return; + } + + var approximately = piece.FindIndex(e => IsOperator(e, "≈")); + var kept = approximately >= 0 ? piece.Take(approximately).ToList() : piece; + var equals = kept.FindLastIndex(e => IsOperator(e, "=")); + if (equals >= 0) + kept = kept.Skip(equals + 1).ToList(); + var value = new XElement(ns + "math", new XElement(ns + "mrow", kept.Select(e => new XElement(e)))); + if (kept.Count > 0 && !values.Any(v => XNode.DeepEquals(v, value))) + values.Add(value); + piece = new List(); + } + } + + private static readonly Dictionary Entities = new Dictionary(StringComparer.Ordinal) + { + ["ApplyFunction"] = "\u2061", ["af"] = "\u2061", ["InvisibleTimes"] = "\u2062", ["it"] = "\u2062", + ["InvisibleComma"] = "\u2063", ["ic"] = "\u2063", ["CenterDot"] = "·", ["middot"] = "·", ["times"] = "×", + ["ImaginaryI"] = "ⅈ", ["ii"] = "ⅈ", ["ExponentialE"] = "ⅇ", ["ee"] = "ⅇ", ["DifferentialD"] = "ⅆ", ["dd"] = "ⅆ", + ["pi"] = "π", ["infin"] = "∞", ["minus"] = "−", ["PlusMinus"] = "±", ["pm"] = "±", ["MinusPlus"] = "∓", + ["approx"] = "≈", ["ne"] = "≠", ["le"] = "≤", ["ge"] = "≥", ["Integral"] = "∫", ["Sum"] = "∑", ["Product"] = "∏", + ["radic"] = "√", ["Sqrt"] = "√", ["or"] = "∨", ["and"] = "∧", ["deg"] = "°", ["nbsp"] = "\u00A0", + ["ThinSpace"] = "\u2009", ["MediumSpace"] = "\u205F", ["NegativeThinSpace"] = "", ["ZeroWidthSpace"] = "", + ["LeftBracketingBar"] = "|", ["RightBracketingBar"] = "|", ["VerticalBar"] = "|", ["DoubleRightArrow"] = "⇒", + ["RightArrow"] = "→", ["rarr"] = "→", ["Element"] = "∈", ["isin"] = "∈", ["NotElement"] = "∉", + ["lceil"] = "⌈", ["rceil"] = "⌉", ["lfloor"] = "⌊", ["rfloor"] = "⌋", ["lang"] = "⟨", ["rang"] = "⟩", + ["NotEqual"] = "≠", ["LessEqual"] = "≤", ["GreaterEqual"] = "≥", ["leq"] = "≤", ["geq"] = "≥", + ["Nscr"] = "𝒩", ["Zopf"] = "ℤ", ["integers"] = "ℤ", ["Ropf"] = "ℝ", ["reals"] = "ℝ", ["Copf"] = "ℂ", + ["complexes"] = "ℂ", ["Nopf"] = "ℕ", ["naturals"] = "ℕ", ["Qopf"] = "ℚ", + }; + + // a piece that is a condition (a≠0, n∈ℤ) or a family of values with a parameter (2π𝒩₁): not a value + private static readonly string[] NotValues = { "≠", "<", ">", "≤", "≥", "∈", "∉", "𝒩", "ℤ", "ℕ", "ℝ", "ℂ", "ℚ" }; + + private static bool IsNotValue(string text) => NotValues.Any(n => text.Contains(n, StringComparison.Ordinal)); + + /// + /// The MathML of the engine with its named entities (&InvisibleTimes;, &ImaginaryI;…) + /// written as their characters, since XML knows only five of them. + /// + public static string DecodeEntities(string mathML) => + Regex.Replace(mathML, "&([A-Za-z][A-Za-z0-9]*);", m => Entities.TryGetValue(m.Groups[1].Value, out var c) ? c : m.Value); + + private static readonly string[] Functions = + { + "arcsin", "arccos", "arctan", "arccot", "arcsec", "arccsc", "sinh", "cosh", "tanh", "coth", "sin", "cos", "tan", + "cot", "sec", "csc", "ln", "log", "exp", "abs", "sqrt", "floor", "ceiling", "sign", "pi", "oo", + }; + + /// + /// The values of a result in the linear format of the engine (x=1, x=-4, xcos(x)+sin(x), + /// ⦗⦗sin⦘^⦗-1⦘⦘(x)), read by AngouriMath: the pieces between commas, semicolons, “or” and “and”, each + /// the right side of its last =, without what follows ≈; ± gives two values. + /// + /// A piece AngouriMath cannot read. + public static IReadOnlyList ReadLinear(string text) + { + var values = new List(); + var seen = new HashSet(StringComparer.Ordinal); + foreach (var piece in Pieces(Plain(text)).SelectMany(Unwrapped)) + { + if (IsNotValue(piece)) + continue; + var kept = piece; + if (kept.IndexOf('≈') is >= 0 and var approximately) + kept = kept[..approximately]; + var name = ""; + if (kept.LastIndexOf('=') is >= 0 and var equals) + (name, kept) = (kept[..equals], kept[(equals + 1)..]); + if (kept.Length == 0) + continue; + foreach (var variant in Signs(kept)) + { + var input = Implicit(variant); + Entity value; + try + { + value = MathS.FromString(input, useCache: false); + } +#pragma warning disable CA1031 // any failure of the parser is the same: not a value + catch (Exception e) when (e is not OutOfMemoryException) +#pragma warning restore CA1031 + { + throw new FormatException("Not a value: “" + variant + "” (" + input + ").", e); + } + if (seen.Add(name + "=" + value.ToString())) + values.Add(value); + } + } + return values; + } + + // the values of a solution of a system, (x=2,y=1), one by one + private static IEnumerable Unwrapped(string piece) + { + if (piece.Length > 1 && piece[0] == '(' && Closing(piece, 0) == piece.Length - 1) + { + var inner = Pieces(piece[1..^1]).ToList(); + if (inner.Count > 1 || inner[0].Contains('=', StringComparison.Ordinal)) + return inner.SelectMany(Unwrapped); + } + return new[] { piece }; + } + + /// + /// The expression with its products and powers of sines and cosines written as sines and cosines of multiple + /// angles (2 sin x cos x is sin(2x)), by MathNet.Symbolics, when that is simpler; else the same (also when + /// either library cannot read the other). + /// + public static Entity Contracted(Entity value) + { + if (!value.Nodes.Any(n => n is Entity.Sinf or Entity.Cosf)) + return value; + try + { + var contracted = MathS.FromString(Infix.Format(Trigonometric.Contract(Infix.ParseOrThrow(Linear(value)))), useCache: false); + return contracted.Complexity < value.Complexity ? contracted : value; + } + catch (Exception) + { + return value; + } + } + + /// The text with two letters swapped, where they are not part of a longer name. + public static string Swapped(string text, string a, string b) => + Regex.Replace(text, "(? m.Value == a ? b : a); + + /// MathML with the identifiers of two letters swapped. + public static string SwappedMathML(string mathML, string a, string b) => + Regex.Replace(mathML, "(]*>)\\s*(" + Regex.Escape(a) + "|" + Regex.Escape(b) + ")\\s*()", + m => m.Groups[1].Value + (m.Groups[2].Value == a ? b : a) + m.Groups[3].Value); + + // the text without the invisible brackets and with the letters AngouriMath reads + private static string Plain(string text) + { + // ⦗⦗sin⦘^⦗-1⦘⦘(x) is arcsin(x), ⦗⦗sin⦘^⦗2⦘⦘(x) is (sin(x))^2 + text = Regex.Replace(text, "⦗⦗(sinh|cosh|tanh|coth|sin|cos|tan|cot|sec|csc)⦘\\^⦗-1⦘⦘(?=\\()", "arc$1"); + // b⦗⦗c⦘^⦗-1⦘⦘ is b/c + text = Regex.Replace(text, "(?<=[\\p{L}\\p{N})⦘!π∞])⦗⦗([^⦗⦘]+)⦘\\^⦗-([^⦗⦘]+)⦘⦘(?!\\()", m => "/(" + m.Groups[1].Value + (m.Groups[2].Value == "1" ? ")" : ")^(" + m.Groups[2].Value + ")")); + text = Bars(text); + for (var m = Regex.Match(text, "⦗⦗([a-z]+)⦘\\^⦗([^⦗⦘]+)⦘⦘\\("); m.Success; m = Regex.Match(text, "⦗⦗([a-z]+)⦘\\^⦗([^⦗⦘]+)⦘⦘\\(")) + { + var open = m.Index + m.Length - 1; + var close = Closing(text, open); + if (close < 0) + break; + text = text[..m.Index] + "((" + m.Groups[1].Value + text[open..(close + 1)] + ")^(" + m.Groups[2].Value + "))" + text[(close + 1)..]; + } + var plain = new StringBuilder(text) + .Replace("⦗", "(").Replace("⦘", ")").Replace(" or ", "∨").Replace(" and ", "∧") + .Replace("π", "pi").Replace("ⅇ", "e").Replace("ⅈ", "i").Replace("∞", "oo").Replace("−", "-") + .Replace("·", "*").Replace("×", "*").Replace("⋅", "*").Replace("\u2062", "*").Replace("\u2061", "") + .Replace("\u00A0", "").Replace(" ", "").Replace("\u2009", ""); + return plain.ToString(); + } + + // |x| is abs(x): a bar after a value or a closing bracket closes, any other opens + private static string Bars(string text) + { + var written = new StringBuilder(); + var open = 0; + for (var i = 0; i < text.Length; i++) + { + if (text[i] != '|') + { + written.Append(text[i]); + continue; + } + + var before = written.ToString().TrimEnd(); + var closes = open > 0 && before.Length > 0 && (char.IsLetterOrDigit(before[^1]) || before[^1] is ')' or '⦘' or '!' or 'π' or 'ⅇ' or 'ⅈ' or '∞'); + written.Append(closes ? ")" : "abs("); + open += closes ? -1 : 1; + } + return written.ToString(); + } + + private static int Closing(string text, int open) + { + var depth = 0; + for (var i = open; i < text.Length; i++) + { + if (text[i] is '(' or '⦗') + depth++; + else if (text[i] is ')' or '⦘' && --depth == 0) + return i; + } + return -1; + } + + // the pieces between separators outside of brackets + private static IEnumerable Pieces(string text) + { + var depth = 0; + var start = 0; + for (var i = 0; i < text.Length; i++) + { + switch (text[i]) + { + case '(' or '[' or '{': + depth++; + break; + case ')' or ']' or '}': + depth--; + break; + case ',' or ';' or '∨' or '∧' when depth == 0: + yield return text[start..i]; + start = i + 1; + break; + } + } + yield return text[start..]; + } + + private static readonly System.Buffers.SearchValues PlusMinus = System.Buffers.SearchValues.Create("±∓"); + + // a ± (or ∓) gives the value with + and the one with - + private static IEnumerable Signs(string text) + { + var at = text.IndexOfAny(PlusMinus); + if (at < 0) + return new[] { text }; + var (first, second) = text[at] == '±' ? ('+', '-') : ('-', '+'); + return Signs(text[..at] + first + text[(at + 1)..]).Concat(Signs(text[..at] + second + text[(at + 1)..])); + } + + private enum Token + { + Value, + Function, + Open, + Close, + Other, + } + + // the products the engine writes without a sign (2x, xcos(x), (x-1)(x+1)) with *, for AngouriMath + private static string Implicit(string text) + { + var tokens = new List<(Token Kind, string Text)>(); + for (var i = 0; i < text.Length;) + { + var c = text[i]; + if (char.IsDigit(c) || c == '.') + { + var end = i; + while (end < text.Length && (char.IsDigit(text[end]) || text[end] == '.')) + end++; + tokens.Add((Token.Value, text[i..end])); + i = end; + } + else if (char.IsLetter(c)) + { + var end = i; + while (end < text.Length && char.IsLetter(text[end])) + end++; + for (var p = i; p < end;) + { + var run = text[p..end]; + var name = Functions.FirstOrDefault(f => run.StartsWith(f, StringComparison.Ordinal)); + if (name is "pi" or "oo") + tokens.Add((Token.Value, name)); + else if (name != null) + tokens.Add((Token.Function, name)); + else + tokens.Add((Token.Value, run[..1])); + p += name?.Length ?? 1; + } + i = end; + } + else + { + tokens.Add((c switch { '(' => Token.Open, ')' => Token.Close, '√' => Token.Function, _ => Token.Other }, c == '√' ? "sqrt" : c.ToString())); + i++; + } + } + + var written = new StringBuilder(); + var previous = Token.Other; + var previousText = ""; + for (var k = 0; k < tokens.Count; k++) + { + var (kind, word) = tokens[k]; + var ends = previous is Token.Value or Token.Close || previousText == "!"; + if (ends && kind is Token.Value or Token.Function or Token.Open) + written.Append('*'); + // √2 and √x: the root of what follows + if (kind == Token.Function && word == "sqrt" && k + 1 < tokens.Count && tokens[k + 1].Kind == Token.Value) + { + written.Append("sqrt(").Append(tokens[k + 1].Text).Append(')'); + k++; + (previous, previousText) = (Token.Close, ")"); + continue; + } + written.Append(word); + (previous, previousText) = (kind, word); + } + return written.ToString(); + } + + private static bool IsSeparator(XElement e) => + IsOperator(e, ",", ";", "∨", "or") || (e.Name.LocalName == "mtext" && e.Value.Trim() == "or"); + + private static bool IsOperator(XElement e, params string[] texts) => + e.Name.LocalName == "mo" && texts.Contains(e.Value.Trim()); + + /// The processor of a Windows library (0x8664 for x64, 0x14C for x86), or null if it is not one. + public static ushort? Machine(Stream library) + { + using var reader = new BinaryReader(library, System.Text.Encoding.ASCII, leaveOpen: true); + if (library.Length < 0x40 || reader.ReadUInt16() != 0x5A4D) + return null; + library.Position = 0x3C; + var header = reader.ReadInt32(); + if (header < 0 || header + 6 > library.Length) + return null; + library.Position = header; + if (reader.ReadUInt32() != 0x00004550) + return null; + return reader.ReadUInt16(); + } + } +} diff --git a/samples/SharpEquations.MathTools.MathEngine/NativeMethods.cs b/samples/SharpEquations.MathTools.MathEngine/NativeMethods.cs new file mode 100644 index 0000000..d599315 --- /dev/null +++ b/samples/SharpEquations.MathTools.MathEngine/NativeMethods.cs @@ -0,0 +1,91 @@ +namespace SharpEquations.MathTools.MathEngine +{ + using System; + using System.Runtime.InteropServices; + + /// + /// The functions of mathenginen.dll the adapter calls. Each returns a code, 0 when it succeeded (see + /// ); the expressions are numbers the context gives and takes back. + /// + internal static class NativeMethods + { + internal const string Library = "mathenginen.dll"; + + [DllImport(Library, CharSet = CharSet.Unicode)] + [DefaultDllImportSearchPaths(DllImportSearchPath.SafeDirectories)] + internal static extern int CreateContext(Guid key, out Guid context); + + [DllImport(Library, CharSet = CharSet.Unicode)] + [DefaultDllImportSearchPaths(DllImportSearchPath.SafeDirectories)] + internal static extern int DestroyContext(Guid context); + + [DllImport(Library, CharSet = CharSet.Unicode)] + [DefaultDllImportSearchPaths(DllImportSearchPath.SafeDirectories)] + internal static extern int SetParsingOptions( + Guid context, + int inputFormat, + [MarshalAs(UnmanagedType.Bool)] bool allowImplicitBrackets, + [MarshalAs(UnmanagedType.Bool)] bool allowMetaCommands, + [MarshalAs(UnmanagedType.Bool)] bool autoCloseParentheses, + int equationParsingMode); + + [DllImport(Library, CharSet = CharSet.Unicode)] + [DefaultDllImportSearchPaths(DllImportSearchPath.SafeDirectories)] + internal static extern int SetEvaluationProperties( + Guid context, + int numberField, + int trigUnitMode, + [MarshalAs(UnmanagedType.Bool)] bool isNumericEvaluation, + [MarshalAs(UnmanagedType.Bool)] bool parsingOnly, + [MarshalAs(UnmanagedType.Bool)] bool useConstantInIntegrationResult, + [MarshalAs(UnmanagedType.Bool)] bool typesetResult); + + [DllImport(Library, CharSet = CharSet.Unicode)] + [DefaultDllImportSearchPaths(DllImportSearchPath.SafeDirectories)] + internal static extern int SetFormatingOptions( + Guid context, + int outputFormat, + int digits, + double scientificHigh, + double scientificLow, + [MarshalAs(UnmanagedType.BStr)] string mathMLPrefix, + [MarshalAs(UnmanagedType.Bool)] bool forWorksheetEntry, + int verbosity); + + [DllImport(Library, CharSet = CharSet.Unicode)] + [DefaultDllImportSearchPaths(DllImportSearchPath.SafeDirectories)] + internal static extern int Parse(Guid context, [MarshalAs(UnmanagedType.BStr)] string text, out int expression); + + [DllImport(Library, CharSet = CharSet.Unicode)] + [DefaultDllImportSearchPaths(DllImportSearchPath.SafeDirectories)] + internal static extern int GetParsingErrorRange(Guid context, out int start, out int length); + + [DllImport(Library, CharSet = CharSet.Unicode)] + [DefaultDllImportSearchPaths(DllImportSearchPath.SafeDirectories)] + internal static extern int ExecuteExpression(Guid context, int expression, out int result); + + [DllImport(Library, CharSet = CharSet.Unicode)] + [DefaultDllImportSearchPaths(DllImportSearchPath.SafeDirectories)] + internal static extern int Serialize(Guid context, int expression, [MarshalAs(UnmanagedType.BStr)] out string text); + + [DllImport(Library, CharSet = CharSet.Unicode)] + [DefaultDllImportSearchPaths(DllImportSearchPath.SafeDirectories)] + internal static extern int DestroyExpression(Guid context, int expression); + + [DllImport(Library, CharSet = CharSet.Unicode)] + [DefaultDllImportSearchPaths(DllImportSearchPath.SafeDirectories)] + internal static extern int CreateEquationRequest(Guid context, int expression, out int request); + + [DllImport(Library, CharSet = CharSet.Unicode)] + [DefaultDllImportSearchPaths(DllImportSearchPath.SafeDirectories)] + internal static extern int EquationRequestRequireVariableList(Guid context, int request, [MarshalAs(UnmanagedType.Bool)] out bool required); + + [DllImport(Library, CharSet = CharSet.Unicode)] + [DefaultDllImportSearchPaths(DllImportSearchPath.SafeDirectories)] + internal static extern int EquationRequestSetVarNames(Guid context, int request, [MarshalAs(UnmanagedType.BStr)] string names); + + [DllImport(Library, CharSet = CharSet.Unicode)] + [DefaultDllImportSearchPaths(DllImportSearchPath.SafeDirectories)] + internal static extern int FullSimplifyExpression(Guid context, int expression, out int result); + } +} diff --git a/samples/SharpEquations.MathTools.MathEngine/SharpEquations.MathTools.MathEngine.csproj b/samples/SharpEquations.MathTools.MathEngine/SharpEquations.MathTools.MathEngine.csproj new file mode 100644 index 0000000..5831fd8 --- /dev/null +++ b/samples/SharpEquations.MathTools.MathEngine/SharpEquations.MathTools.MathEngine.csproj @@ -0,0 +1,22 @@ + + + + + net10.0 + false + enable + SharpEquations.MathTools.MathEngine + + + + + + + + + + + + diff --git a/tests/SharpEquations.MathTools.Tests/MathEngineTests.cs b/tests/SharpEquations.MathTools.Tests/MathEngineTests.cs new file mode 100644 index 0000000..0de1e3e --- /dev/null +++ b/tests/SharpEquations.MathTools.Tests/MathEngineTests.cs @@ -0,0 +1,242 @@ +namespace SharpEquations.MathTools.Tests +{ + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Threading.Tasks; + using AngouriMath; + using SharpEquations; + using SharpEquations.MathTools; + using SharpEquations.MathTools.MathEngine; + + /// + /// The adapter of the engine of Microsoft Mathematics: what it writes and reads (everywhere), and the reference cases + /// of the computer algebra done by the engine itself, only on Windows with Microsoft Mathematics installed (or + /// MATHENGINEN_PATH set), skipped elsewhere. + /// + public class MathEngineTests + { + private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(20); + + // what the engine itself does not do + private const string SeriesLimit = "The engine of Microsoft Mathematics gives this series to infinity back as it is."; + + private static readonly Dictionary Limits = new Dictionary(StringComparer.Ordinal) + { + ["Evaluate ∑_(k=1)^∞ 1/k^4"] = SeriesLimit, + ["Evaluate ∑_(k=1)^∞ 1/(k(k+1))"] = SeriesLimit, + ["Evaluate ∑_(k=1)^∞ 1/(k(k+2))"] = SeriesLimit, + ["Evaluate ∑_(k=1)^∞ 1/(4k^2-1)"] = SeriesLimit, + ["Evaluate ∑_(k=0)^∞ 1/(2k+1)^2"] = SeriesLimit, + ["Evaluate ∑_(k=1)^∞ 1/(k^2 (k+1))"] = SeriesLimit, + ["Evaluate ∑_(k=1)^∞ (-1)^(k+1)/k"] = SeriesLimit, + ["Evaluate ∑_(k=1)^∞ (-1)^(k+1)/k^2"] = SeriesLimit, + ["Evaluate ∑_(k=0)^∞ (-1)^k/(2k+1)"] = SeriesLimit, + ["Evaluate ∑_(k=0)^∞ (-1)^k/(2k+1)^3"] = SeriesLimit, + ["Evaluate ∑_(k=0)^∞ 1/((3k+1)(3k+2))"] = SeriesLimit, + ["Evaluate ∑_(k=0)^∞ (-1)^k/(3k+1)"] = SeriesLimit, + ["Evaluate ∑_(k=1)^∞ 1/(k^2+1)"] = SeriesLimit, + }; + + [Test] + [Arguments("x^2+3*x-4", "x^2+3*x-4")] + [Arguments("sin(x)^2", "sin(x)^2")] + [Arguments("(x+1)/(x-1)", "(x+1)/(x-1)")] + [Arguments("x-(y-1)", "x-(y-1)")] + [Arguments("(-2)^x", "(-2)^x")] + [Arguments("2^(1/2)", "2^(1/2)")] + [Arguments("ln(x)", "ln(x)")] + [Arguments("log(2, x)", "ln(x)/ln(2)")] + [Arguments("abs(x-pi)", "abs(x-pi)")] + [Arguments("x!", "x!")] + [Arguments("-x+1", "-x+1")] + [Arguments("x-2*y", "x-2*y")] + [Arguments("1+(-3)*x", "1-3*x")] + [Arguments("floor(x)+ceil(x)", "floor(x)+ceiling(x)")] + [Arguments("sign(x)", "sign(x)")] + [Arguments("arcsec(x)", "arcsec(x)")] + public async Task WritesLinearInput(string angouri, string expected) + { + await Assert.That(MathEngineText.Linear(MathS.FromString(angouri, useCache: false))).IsEqualTo(expected); + } + + [Test] + public async Task WritesSumsProductsIntegralsAndCombinations() + { + Entity k = "k"; + Entity x = "x"; + await Assert.That(MathEngineText.Linear(new Entity.Summationf(k.Pow(2), k, 1, 10))).IsEqualTo("seriesSum(k^2,k,1,10)"); + await Assert.That(MathEngineText.Linear(new Entity.Productf(k, k, 1, 5))).IsEqualTo("seriesProduct(k,k,1,5)"); + await Assert.That(MathEngineText.Linear(new Entity.Integralf(x, x, (0, 1)))).IsEqualTo("integral(x,x,0,1)"); + await Assert.That(MathEngineText.Linear(new Entity.Binomialf(5, 2))).IsEqualTo("combination(5,2)"); + } + + [Test] + [Arguments("x=1, x=-4", new[] { "1", "-4" })] + [Arguments("xcos(x)+sin(x)", new[] { "x*cos(x)+sin(x)" })] + [Arguments("2xcos(⦗⦗x⦘^⦗2⦘⦘)", new[] { "2*x*cos(x^2)" })] + [Arguments("(ln(x)+1)⦗⦗x⦘^⦗x⦘⦘", new[] { "(ln(x)+1)*x^x" })] + [Arguments("x(x-1)(x+1)", new[] { "x*(x-1)*(x+1)" })] + [Arguments("(x-2)(⦗⦗x⦘^⦗2⦘⦘+2x+4)", new[] { "(x-2)*(x^2+2*x+4)" })] + [Arguments("xln(x)-x", new[] { "x*ln(x)-x" })] + [Arguments("⦗⦗ln(⦗⦗x⦘^⦗2⦘⦘+1)⦘/⦗2⦘⦘", new[] { "ln(x^2+1)/2" })] + [Arguments("⦗⦗(sec(x))⦘^⦗2⦘⦘", new[] { "sec(x)^2" })] + [Arguments("ln(⦗⦗e⦘^⦗2x⦘⦘)", new[] { "2*x" })] + [Arguments("⦗⦗sin⦘^⦗-1⦘⦘(x)", new[] { "arcsin(x)" })] + [Arguments("⦗⦗sin⦘^⦗2⦘⦘(x)", new[] { "sin(x)^2" })] + [Arguments("x=1±√2", new[] { "1+sqrt(2)", "1-sqrt(2)" })] + [Arguments("x=2π or x=−ⅈ", new[] { "2*pi", "-i" })] + [Arguments("x=3, y=1", new[] { "3", "1" })] + [Arguments("x=√2≈1.414", new[] { "sqrt(2)" })] + [Arguments("x=-⦗⦗b⦘/⦗a⦘⦘,a<>0", new[] { "-b/a" })] + [Arguments("x=-⦗⦗b⦘/⦗a⦘⦘ and a≠0", new[] { "-b/a" })] + [Arguments("(x=2, y=1)", new[] { "2", "1" })] + [Arguments("(x=1, y=2) or (x=-1, y=-2)", new[] { "1", "2", "-1", "-2" })] + [Arguments("x=-1 or x=-1", new[] { "-1" })] + [Arguments("x=3, x=3+⦗⦗2π𝒩₁ⅈ⦘/⦗ln(2)⦘⦘, 𝒩₁∈ℤ", new[] { "3" })] + [Arguments("(x=1, y=1, z=4)", new[] { "1", "1", "4" })] + [Arguments("b⦗⦗c⦘^⦗-1⦘⦘", new[] { "b/c" })] + [Arguments("ln(|x|)", new[] { "ln(abs(x))" })] + [Arguments("|x-1|+2|x|", new[] { "abs(x-1)+2*abs(x)" })] + public async Task ReadsLinearResults(string text, string[] expected) + { + var values = MathEngineText.ReadLinear(text); + await Assert.That(values.Count).IsEqualTo(expected.Length); + for (var i = 0; i < expected.Length; i++) + await Assert.That(Reference.Same(values[i], MathS.FromString(expected[i], useCache: false))).IsTrue(); + } + + [Test] + public async Task ReadsNegativePowersAsQuotients() + { + await Assert.That(MathEngineText.ReadLinear("b⦗⦗c⦘^⦗-1⦘⦘")[0]).IsTypeOf(); + await Assert.That(MathEngineText.ReadLinear("x⦗⦗y⦘^⦗-2⦘⦘")[0]).IsTypeOf(); + } + + [Test] + [Arguments("2*sin(x)*cos(x)", "sin(2*x)")] + [Arguments("cos(x)^2-sin(x)^2", "cos(2*x)")] + [Arguments("1-2*sin(x)^2", "cos(2*x)")] + [Arguments("sin(x)^2+x", "sin(x)^2+x")] + [Arguments("x+1", "x+1")] + public async Task ContractsSinesAndCosines(string input, string expected) + { + var contracted = MathEngineText.Contracted(MathS.FromString(input, useCache: false)); + await Assert.That(contracted == MathS.FromString(expected, useCache: false)).IsTrue(); + } + + [Test] + public async Task SwapsLetters() + { + await Assert.That(MathEngineText.Swapped("x=√(25-y^2) or x=exp(y)", "x", "y")).IsEqualTo("y=√(25-x^2) or y=exp(x)"); + await Assert.That(MathEngineText.SwappedMathML("x=ymax", "x", "y")) + .IsEqualTo("y=xmax"); + } + + [Test] + public async Task DecodesNamedEntities() + { + await Assert.That(MathEngineText.DecodeEntities("ⅈ⁢&")) + .IsEqualTo("ⅈ\u2062&"); + const string result = "x=2·ⅈ"; + await Assert.That(MathEngineText.Values(result).Count).IsEqualTo(1); + const string family = "x=3," + + "x=3,x=𝒩1," + + "a≠0"; + await Assert.That(MathEngineText.Values(family).Count).IsEqualTo(1); + } + + [Test] + public async Task WritesRationalsInBrackets() + { + await Assert.That(MathEngineText.Linear(Entity.Number.Rational.Create(1, 2) * "x")).IsEqualTo("(1/2)*x"); + } + + [Test] + public async Task WritesCommands() + { + Entity f = "x^2"; + await Assert.That(MathEngineText.Command(CasAction.Evaluate, new[] { f }, null)).IsEqualTo("x^2"); + await Assert.That(MathEngineText.Command(CasAction.Factor, new[] { f }, null)).IsEqualTo("factor(x^2)"); + await Assert.That(MathEngineText.Command(CasAction.Differentiate, new[] { f }, "x")).IsEqualTo("deriv(x^2,x)"); + await Assert.That(MathEngineText.Command(CasAction.Integrate, new[] { f }, "x")).IsEqualTo("integral(x^2,x)"); + await Assert.That(MathEngineText.Command(CasAction.Solve, new[] { f }, "x")).IsEqualTo("x^2=0"); + Entity a = MathS.Equality("x+y", 3); + Entity b = MathS.Equality("x-y", 1); + await Assert.That(MathEngineText.Command(CasAction.Solve, new[] { a, b }, null)).IsEqualTo("x+y=3, x-y=1"); + await Assert.That(() => MathEngineText.Command(CasAction.Simplify, new[] { a, b }, null)).Throws(); + await Assert.That(MathEngineText.SolveCommand(new[] { "Equal[x,1]", "Equal[y,2]" })).IsEqualTo("SymbolicSolve[List[Equal[x,1],Equal[y,2]]]"); + } + + [Test] + public async Task DecodesErrors() + { + await Assert.That(MathEngineText.Error(0)).IsNull(); + await Assert.That(MathEngineText.Error(2 << 16)).IsEqualTo("The computation was stopped."); + await Assert.That(MathEngineText.Error((1 << 16) | 7)!).Contains("cannot read this (error -3)"); + await Assert.That(MathEngineText.Error(8)!).Contains("cannot compute this (error 4)"); + } + + [Test] + public async Task SplitsValues() + { + const string result = "x=1" + + ",x=-4orx=2" + + "≈1.414"; + var values = MathEngineText.Values(result); + await Assert.That(values.Count).IsEqualTo(3); + await Assert.That(values[0].Value).IsEqualTo("1"); + await Assert.That(values[1].Value).IsEqualTo("-4"); + await Assert.That(values[2].Descendants().Any(e => e.Name.LocalName == "msqrt")).IsTrue(); + await Assert.That(values.All(v => v.Name.LocalName == "math")).IsTrue(); + foreach (var value in values) + await Assert.That(Equation.TryParse(value.ToString(), EquationFormat.MathML, null, out _)).IsTrue(); + } + + [Test] + public async Task ReadsTheMachine() + { + var image = new byte[0x100]; + image[0] = (byte)'M'; + image[1] = (byte)'Z'; + BitConverter.GetBytes(0x80).CopyTo(image, 0x3C); + image[0x80] = (byte)'P'; + image[0x81] = (byte)'E'; + BitConverter.GetBytes((ushort)0x8664).CopyTo(image, 0x84); + using (var stream = new MemoryStream(image)) + await Assert.That(MathEngineText.Machine(stream)).IsEqualTo((ushort)0x8664); + using (var text = new MemoryStream(new byte[0x100])) + await Assert.That(MathEngineText.Machine(text)).IsNull(); + } + + [Test] + public async Task IsNotAvailableWithoutWindows() + { + if (!OperatingSystem.IsWindows()) + await Assert.That(MathEngineN.IsAvailable).IsFalse(); + } + + [Test] + [MethodDataSource(typeof(CasCase), nameof(CasCase.Names))] + public async Task ComputesLikeTheReference(string name) + { + if (!MathEngineN.IsAvailable) + Skip.Test("The engine of Microsoft Mathematics is not installed (Windows, or MATHENGINEN_PATH)."); + var test = CasCase.Named(name); + if (test.Pending != null) + Skip.Test(test.Pending); + if (Limits.TryGetValue(name, out var limit)) + Skip.Test(limit); + var input = Equation.Parse(test.Input, EquationFormat.UnicodeMath, new EquationOptions { Display = true }); + using var engine = new MathEngineN { Angles = test.Angles }; + foreach (var definition in test.Definitions) + engine.Run(CasAction.Define, Equation.Parse(definition, EquationFormat.UnicodeMath)); + var work = Task.Run(() => engine.Run(test.Action, input, test.Variable)); + if (await Task.WhenAny(work, Task.Delay(Timeout)) != work) + Assert.Fail("No result in " + Timeout.TotalSeconds + " seconds."); + var result = await work; + await Assert.That(Reference.Check(test, result)).IsNull(); + } + } +} diff --git a/tests/SharpEquations.MathTools.Tests/SeriesTests.cs b/tests/SharpEquations.MathTools.Tests/SeriesTests.cs new file mode 100644 index 0000000..0a578d5 --- /dev/null +++ b/tests/SharpEquations.MathTools.Tests/SeriesTests.cs @@ -0,0 +1,93 @@ +namespace SharpEquations.MathTools.Tests +{ + using System; + using System.Linq; + using System.Threading.Tasks; + using AngouriMath; + using SharpEquations.MathTools; + + /// The sums to infinity of a known form, each by its value. + public class SeriesTests + { + private static Entity? Sum(string body, long from) => + Series.Value((Entity.Summationf)MathS.Sum(MathS.FromString(body), MathS.Var("k"), from, MathS.oo)); + + /// A sum with a known value is that value exactly: no sum is left, and it is the decimal expected. + [Test] + [Arguments("1/k^2", 1, 1.6449340668482264)] + [Arguments("k^(-2)", 1, 1.6449340668482264)] + [Arguments("3/k^2", 1, 4.934802200544679)] + [Arguments("1/k^2", 3, 0.3949340668482264)] + [Arguments("1/k^4", 1, 1.0823232337111381)] + [Arguments("1/k^6", 1, 1.0173430619844491)] + [Arguments("1/k^12", 1, 1.000246086553308)] + [Arguments("(-1)^(k+1)/k", 1, 0.6931471805599453)] + [Arguments("(-1)^k/k^2", 1, -0.8224670334241132)] + [Arguments("(-1)^k/(2k+1)", 0, 0.7853981633974483)] + [Arguments("(-1)^k/(2k+1)^3", 0, 0.9689461462593693)] + [Arguments("1/(k(k+1))", 1, 1.0)] + [Arguments("1/(k^2+3k+2)", 0, 1.0)] + [Arguments("1/(k(k+2))", 1, 0.75)] + [Arguments("1/(4k^2-1)", 1, 0.5)] + [Arguments("1/k^2+1/2^k", 1, 2.6449340668482264)] + [Arguments("1/(k(k+1)(k+2))", 1, 0.25)] + [Arguments("1/(k^2(k+1))", 1, 0.6449340668482264)] + [Arguments("1/(2k+1)^2", 0, 1.2337005501361697)] + [Arguments("1/((3k+1)(3k+2))", 0, 0.6045997880780726)] + [Arguments("1/((5k+1)(5k+2))", 0, 0.5455310704014045)] + [Arguments("(-1)^k/(3k+1)", 0, 0.8356488482647211)] + [Arguments("1/k^2+(-1)^k/k^2", 1, 0.8224670334241132)] + [Arguments("1/(k^2+1)", 1, 1.076674047468581)] + [Arguments("1/(k^2+1)", 0, 2.076674047468581)] + [Arguments("1/(k^2-2)", 1, -0.056810407700620236)] + [Arguments("1/(k^2+k+1)", 0, 1.7981472805626901)] + [Arguments("1/(k^2+2k+3)", 2, 0.3610281005734779)] + [Arguments("(-1)^k/(k^2+1)", 0, 0.6360145274910666)] + [Arguments("(-1)^k/(k^2+4)", 3, -0.04706661758669953)] + [Arguments("2/(pi*k^2)", 1, 1.0471975511965976)] + [Arguments("1/k^2-1/k^4", 1, 0.5626108331370883)] + [Arguments("1/(k^2-1/4)", 1, 2.0)] + [Arguments("(-1)^k/(2k+1)^5", 0, 0.9961578280770881)] + public async Task SumsAKnownSeries(string body, long from, double expected) + { + var value = Sum(body, from); + await Assert.That(value).IsNotNull(); + await Assert.That(value!.Nodes.Any(n => n is Entity.Summationf)).IsFalse(); + var number = ((Entity.Number.Complex)value.EvalNumerical()).RealPart.EDecimal.ToDouble(); + await Assert.That(Math.Abs(number - expected)).IsLessThan(1e-9 * Math.Max(1, Math.Abs(expected))); + } + + /// A sum whose terms do not go to zero fast enough has no end. + [Test] + public async Task TheHarmonicSeriesDiverges() + { + await Assert.That(Sum("1/k", 1)).IsEqualTo(MathS.oo); + await Assert.That(Sum("-2/k", 5)).IsEqualTo(-MathS.oo); + await Assert.That(Sum("k/(k^2+1)", 0)).IsEqualTo(MathS.oo); + await Assert.That(Sum("-1/(2k+1)", 0)).IsEqualTo(-MathS.oo); + await Assert.That(Sum("k^2", 1)).IsEqualTo(MathS.oo); + } + + /// + /// A sum with no known closed form is left as it is: ζ(3), a term of another form, one that is not a number at an + /// index, and one that goes up and down without end. + /// + [Test] + [Arguments("1/k^3", 1)] + [Arguments("(-1)^k/k^3", 1)] + [Arguments("sin(k)/k^2", 1)] + [Arguments("1/(k^3+1)", 1)] + [Arguments("1/(k-3)^2", 1)] + [Arguments("(-1)^k", 0)] + public async Task LeavesAnUnknownSeries(string body, long from) => await Assert.That(Sum(body, from)).IsNull(); + + /// The engine evaluates the sum read from UnicodeMath to π²/6. + [Test] + public async Task TheEngineSumsTheBaselSeries() + { + var result = AngouriMathEngine.Run(CasAction.Evaluate, MathReader.Read(Equation.Parse("∑_(k=1)^∞ 1/k^2", EquationFormat.UnicodeMath)), null); + await Assert.That(result.Text).Contains("pi"); + await Assert.That(result.Text).Contains("1.644934"); + } + } +} diff --git a/tests/SharpEquations.MathTools.Tests/SharpEquations.MathTools.Tests.csproj b/tests/SharpEquations.MathTools.Tests/SharpEquations.MathTools.Tests.csproj index cc0ee8e..62af7a9 100644 --- a/tests/SharpEquations.MathTools.Tests/SharpEquations.MathTools.Tests.csproj +++ b/tests/SharpEquations.MathTools.Tests/SharpEquations.MathTools.Tests.csproj @@ -17,6 +17,7 @@ + diff --git a/tests/data/mathtools/cas.json b/tests/data/mathtools/cas.json index 999c6e4..e260774 100644 --- a/tests/data/mathtools/cas.json +++ b/tests/data/mathtools/cas.json @@ -354,8 +354,98 @@ "input": "∑_(k=1)^∞ 1/k^2", "expected": [ "π^2/6" - ], - "pending": "AngouriMath does not sum the series" + ] + }, + { + "action": "Evaluate", + "input": "∑_(k=1)^∞ 1/k^4", + "expected": [ + "π^4/90" + ] + }, + { + "action": "Evaluate", + "input": "∑_(k=1)^∞ 1/(k(k+1))", + "expected": [ + "1" + ] + }, + { + "action": "Evaluate", + "input": "∑_(k=1)^∞ 1/(k(k+2))", + "expected": [ + "3/4" + ] + }, + { + "action": "Evaluate", + "input": "∑_(k=1)^∞ 1/(4k^2-1)", + "expected": [ + "1/2" + ] + }, + { + "action": "Evaluate", + "input": "∑_(k=0)^∞ 1/(2k+1)^2", + "expected": [ + "π^2/8" + ] + }, + { + "action": "Evaluate", + "input": "∑_(k=1)^∞ 1/(k^2 (k+1))", + "expected": [ + "π^2/6-1" + ] + }, + { + "action": "Evaluate", + "input": "∑_(k=1)^∞ (-1)^(k+1)/k", + "expected": [ + "ln 2" + ] + }, + { + "action": "Evaluate", + "input": "∑_(k=1)^∞ (-1)^(k+1)/k^2", + "expected": [ + "π^2/12" + ] + }, + { + "action": "Evaluate", + "input": "∑_(k=0)^∞ (-1)^k/(2k+1)", + "expected": [ + "π/4" + ] + }, + { + "action": "Evaluate", + "input": "∑_(k=0)^∞ (-1)^k/(2k+1)^3", + "expected": [ + "π^3/32" + ] + }, + { + "action": "Evaluate", + "input": "∑_(k=0)^∞ 1/((3k+1)(3k+2))", + "expected": [ + "π/(3√3)" + ] + }, + { + "action": "Evaluate", + "input": "∑_(k=0)^∞ (-1)^k/(3k+1)", + "expected": [ + "(π/√3+ln 2)/3" + ] + }, + { + "action": "Evaluate", + "input": "∑_(k=1)^∞ 1/(k^2+1)", + "expected": [ + "(π (e^(2π)+1)/(e^(2π)-1)-1)/2" + ] }, { "action": "Evaluate",