diff --git a/README.md b/README.md index 50da23a..57068f7 100644 --- a/README.md +++ b/README.md @@ -76,13 +76,32 @@ dotnet run --project tests/GraphTUI.Tests/GraphTUI.Tests.csproj ## Mathematical Syntax -### Expressions & Variables -- Cartesian functions: $y = f(x)$, e.g. `sin(x) * exp(-0.1x)` -- Parametric curves: $x(t) = \cos(3t)$, $y(t) = \sin(4t)$ -- Polar curves: $r = f(\theta)$, e.g. `2*(1 - sin(theta))` -- Implicit multiplication: `2x`, `3sin(x)`, `(x+1)(x-1)`, `2pi`, `x y` +### Expressions & Double-Sided Equations +GraphTUI automatically parses and classifies all single-sided and double-sided definitions: +- **$y = f(x)$ or $f(x) = y$**: Standard Cartesian curves, e.g. `y = sin(x)`, `y = x^2 - 4`, `sin(x) = y` +- **$f(y) = x$ or $x = f(y)$**: Inverse and vertical curves, e.g. `y^2 = x`, `sin(y) = x`, `x = y^2`, `x = cos(y)` +- **$f(y) = g(x)$ or $F(x, y) = 0$**: Double-sided implicit curves & relations, e.g. `y^2 = sin(x)`, `sin(y) = cos(x)`, `y^2 = x^3 - 3x` (elliptic curve), `x^2 + y^2 = 25` (circle), `y^2 - x^2 = 1` (hyperbola) +- **Parametric curves**: $x(t) = \cos(3t)$, $y(t) = \sin(4t)$ +- **Polar curves**: $r = f(\theta)$, e.g. `2*(1 - sin(theta))` +- **Implicit multiplication**: `2x`, `3sin(x)`, `(x+1)(x-1)`, `2pi`, `x y` -### Built-in Functions +### Calculus, Summation & Product Operations +- **Summation**: `sum(n=start, end, f(n))` or `sum(n, start, end, f(n))` + Example: `sum(n=1, 5, sin(n*x)/n)` (Fourier harmonic synthesis), `sum(k=0, 8, x^k / fact(k))` (Taylor expansion of $e^x$) +- **Product**: `prod(n=start, end, f(n))` or `prod(n, start, end, f(n))` + Example: `prod(n=1, 4, 1 + x/n)` (Weierstrass product) +- **Definite Integrals in Formulas**: `int(t=a, b, f(t))` or `integral(t=a, b, f(t))` + Example: `y = int(t=0, x, sin(t^2))` (Fresnel sine integral), `y = int(t=1, x, 1/t)` (definition of $\ln(x)$) +- **Numerical Derivative Operator**: `diff(t=x, f(t))` or `diff(f(x), x)` + Example: `y = diff(t=x, sin(t^3))` (evaluates $\frac{d}{dx}[\sin(x^3)] = 3x^2 \cos(x^3)$) +- **Factorials, Double & Super Factorials**: + - **Single Factorial**: `x!` or `fact(x)` (e.g. `5! = 120`, `(x+1)!`) + - **Double Factorial**: `x!!` or `dfact(x)` (e.g. `5!! = 15`, `6!! = 48`, with full analytic continuation) + - **Super Factorial**: `x$` or `sfact(x)` (e.g. `4$ = 1!*2!*3!*4! = 288`) + - **Gamma function**: `gamma(x)` (Lanczos approximation for $\Gamma(x)$, accurate to 14 decimal digits) + - **Zero-Lag Line Clipping & Caching**: Powered by Cohen-Sutherland line clipping and static lookup tables ($0! \dots 170!$, $0!! \dots 300!!$, $0\$ \dots 27\$$). Steep factorial growth cannot hang the terminal or trigger off-screen rasterization. + +### Built-in Functions & Constants - **Trigonometric**: `sin`, `cos`, `tan`, `cot`, `sec`, `csc` - **Inverse Trig**: `asin`, `acos`, `atan`, `atan2(y, x)` - **Hyperbolic**: `sinh`, `cosh`, `tanh` @@ -90,6 +109,12 @@ dotnet run --project tests/GraphTUI.Tests/GraphTUI.Tests.csproj - **Rounding & Utilities**: `abs`, `floor`, `ceil`, `round`, `sgn`, `min(a, b)`, `max(a, b)`, `clamp(x, min, max)` - **Constants**: `pi` ($\pi$), `e`, `tau` ($2\pi$), `phi` ($\approx 1.618$) +### Function Cheatsheet (`F5` or `:cheat`) +Press **`F5`** at any time to open the built-in, categorized **Math Cheatsheet**: +- **Tab / 1-5**: Switch categories (Calculus/Sum/Prod, Double-Sided Equations, Trig, Exponentials, Utilities). +- **Up / Down**: Browse formulas, syntax, descriptions, and real-world examples. +- **Enter**: Instantly loads and graphs the selected example! + --- ## Architecture diff --git a/src/GraphTUI/App.cs b/src/GraphTUI/App.cs index 779a25c..f9aa4b3 100644 --- a/src/GraphTUI/App.cs +++ b/src/GraphTUI/App.cs @@ -22,6 +22,7 @@ public sealed class App private readonly PresetsGalleryModal _presetsModal = new(); private readonly CalculusModal _calculusModal = new(); private readonly HelpModal _helpModal = new(); + private readonly CheatsheetModal _cheatsheetModal = new(); private bool _isRunning = true; private bool _traceMode = false; @@ -168,6 +169,18 @@ public sealed class App private void HandleKeyEvent(KeyAction key) { // 1. Modals take priority + if (_cheatsheetModal.IsOpen) + { + _cheatsheetModal.HandleKey(key, expr => + { + ColorRgb color = ColorRgb.Palette[(_nextFunctionId - 1) % ColorRgb.Palette.Length]; + var fn = new GraphFunction(_nextFunctionId++, expr, color); + _functions.Add(fn); + SetStatus($"Loaded from cheatsheet: {fn.GetDisplayFormula()}"); + }); + return; + } + if (_helpModal.IsOpen) { _helpModal.HandleKey(key); @@ -210,6 +223,12 @@ public sealed class App return; } + if (key.Code == KeyCode.F5) + { + _cheatsheetModal.IsOpen = true; + return; + } + if (key.Code == KeyCode.F4 || (key.Code == KeyCode.Char && key.KeyChar is 'p' or 'P')) { _presetsModal.IsOpen = true; @@ -353,15 +372,34 @@ public sealed class App private void UpdateTraceY() { var fn = _functions.FirstOrDefault(f => f.IsVisible && f.CompilationError == null); - if (fn?.Evaluator != null && fn.Type == FunctionType.Cartesian) + if (fn?.Evaluator != null) { - _crosshairY = fn.Evaluator.Evaluate(_crosshairX, GetParamValue); + if (fn.Type == FunctionType.Cartesian) + { + _crosshairY = fn.Evaluator.Evaluate(_crosshairX, GetParamValue); + } + else if (fn.Type == FunctionType.CartesianX) + { + _crosshairX = fn.Evaluator.EvaluateY(_crosshairY, GetParamValue); + } } } private void HandleMouseEvent(MouseEvent mouse) { // 1. Modals mouse handling + if (_cheatsheetModal.IsOpen) + { + _cheatsheetModal.HandleMouse(mouse, _layout.ScreenWidth, _layout.ScreenHeight, expr => + { + ColorRgb color = ColorRgb.Palette[(_nextFunctionId - 1) % ColorRgb.Palette.Length]; + var fn = new GraphFunction(_nextFunctionId++, expr, color); + _functions.Add(fn); + SetStatus($"Loaded from cheatsheet: {fn.GetDisplayFormula()}"); + }); + return; + } + if (_helpModal.IsOpen) { _helpModal.HandleMouse(mouse, _layout.ScreenWidth, _layout.ScreenHeight); @@ -478,7 +516,7 @@ public sealed class App private void PromptAddFunction() { - _commandBar.Open("Add function (e.g. sin(x)): y = ", "", expr => + _commandBar.Open("Add equation (e.g. y=sin(x), y^2=x, y^2=sin(x)): ", "", expr => { if (!string.IsNullOrWhiteSpace(expr)) { @@ -577,6 +615,10 @@ public sealed class App _helpModal.IsOpen = true; break; + case "cheat" or "cheatsheet": + _cheatsheetModal.IsOpen = true; + break; + default: // Treat input as a formula to add ColorRgb color = ColorRgb.Palette[(_nextFunctionId - 1) % ColorRgb.Palette.Length]; @@ -772,7 +814,11 @@ public sealed class App } // 4. Render Modals (if active) - if (_calculusModal.IsOpen) + if (_cheatsheetModal.IsOpen) + { + _cheatsheetModal.Render(_screen, _layout.ScreenWidth, _layout.ScreenHeight); + } + else if (_calculusModal.IsOpen) { _calculusModal.Render(_screen, _layout.ScreenWidth, _layout.ScreenHeight, _crosshairX); } @@ -801,7 +847,7 @@ public sealed class App { string sidebarToggle = _layout.IsSidebarCollapsed ? "[ > ]" : "[ < ]"; string title = "GraphTUI 1.0 (.NET 10)"; - string quickKeys = "F1: Help | F2: Sidebar | F3: Calculus | F4: Presets | : cmd"; + string quickKeys = "F1: Help | F2: Sidebar | F3: Calc | F4: Presets | F5: Cheat | : cmd"; _screen.DrawText(0, 0, new string(' ', _layout.ScreenWidth), ColorRgb.White, ColorRgb.DarkGray); _screen.DrawText(1, 0, sidebarToggle, ColorRgb.Accent, ColorRgb.DarkGray); diff --git a/src/GraphTUI/Core/Math/AstNodes.cs b/src/GraphTUI/Core/Math/AstNodes.cs index a287fbb..2611979 100644 --- a/src/GraphTUI/Core/Math/AstNodes.cs +++ b/src/GraphTUI/Core/Math/AstNodes.cs @@ -1,24 +1,69 @@ namespace GraphTUI.Core.Math; +public sealed class LocalScope +{ + public string Name { get; } + public double Value { get; } + public LocalScope? Parent { get; } + + public LocalScope(string name, double value, LocalScope? parent = null) + { + Name = name.ToLowerInvariant(); + Value = value; + Parent = parent; + } + + public bool TryLookup(string name, out double val) + { + for (var curr = this; curr != null; curr = curr.Parent) + { + if (curr.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) + { + val = curr.Value; + return true; + } + } + val = 0; + return false; + } +} + public readonly struct EvaluationContext { public double X { get; } + public double Y { get; } public double T { get; } public double Theta { get; } + public LocalScope? Scope { get; } public Func? ParameterLookup { get; } - public EvaluationContext(double x = 0, double t = 0, double theta = 0, Func? parameterLookup = null) + public EvaluationContext( + double x = 0, + double y = 0, + double t = 0, + double theta = 0, + LocalScope? scope = null, + Func? parameterLookup = null) { X = x; + Y = y; T = t; Theta = theta; + Scope = scope; ParameterLookup = parameterLookup; } + + public EvaluationContext WithScope(string name, double value) + { + var newScope = new LocalScope(name, value, Scope); + return new EvaluationContext(X, Y, T, Theta, newScope, ParameterLookup); + } } public abstract class AstNode { public abstract double Evaluate(in EvaluationContext ctx); + public virtual void CollectVariables(HashSet vars) { } } public sealed class NumberNode : AstNode @@ -39,6 +84,7 @@ public sealed class VariableNode : AstNode { public string Name { get; } private readonly bool _isX; + private readonly bool _isY; private readonly bool _isT; private readonly bool _isTheta; private readonly double _constantValue; @@ -48,6 +94,7 @@ public sealed class VariableNode : AstNode { Name = name.ToLowerInvariant(); _isX = Name == "x"; + _isY = Name == "y"; _isT = Name == "t"; _isTheta = Name is "theta" or "θ" or "th"; @@ -78,10 +125,24 @@ public sealed class VariableNode : AstNode } } + public override void CollectVariables(HashSet vars) + { + if (!_isConstant) + { + vars.Add(Name); + } + } + public override double Evaluate(in EvaluationContext ctx) { + if (ctx.Scope != null && ctx.Scope.TryLookup(Name, out double localVal)) + { + return localVal; + } + if (_isConstant) return _constantValue; if (_isX) return ctx.X; + if (_isY) return ctx.Y; if (_isT) return ctx.T; if (_isTheta) return ctx.Theta; @@ -119,6 +180,11 @@ public sealed class UnaryOpNode : AstNode return Op == UnaryOperator.Negate ? -val : val; } + public override void CollectVariables(HashSet vars) + { + Operand.CollectVariables(vars); + } + public override string ToString() => Op == UnaryOperator.Negate ? $"-({Operand})" : $"+({Operand})"; } @@ -162,6 +228,12 @@ public sealed class BinaryOpNode : AstNode }; } + public override void CollectVariables(HashSet vars) + { + Left.CollectVariables(vars); + Right.CollectVariables(vars); + } + public override string ToString() => $"({Left} {Op} {Right})"; } @@ -176,6 +248,14 @@ public sealed class FunctionCallNode : AstNode Arguments = arguments; } + public override void CollectVariables(HashSet vars) + { + foreach (var arg in Arguments) + { + arg.CollectVariables(vars); + } + } + public override double Evaluate(in EvaluationContext ctx) { int argCount = Arguments.Length; @@ -214,6 +294,10 @@ public sealed class FunctionCallNode : AstNode "ceil" => System.Math.Ceiling(a0), "round" => System.Math.Round(a0), "sgn" or "sign" => System.Math.Sign(a0), + "gamma" => Gamma(a0), + "fact" or "factorial" => Factorial(a0), + "dfact" or "doublefact" => DoubleFactorial(a0), + "sfact" or "superfact" => SuperFactorial(a0), _ => double.NaN }; @@ -242,5 +326,423 @@ public sealed class FunctionCallNode : AstNode return double.NaN; } + private static readonly double[] FactorialTable = InitializeFactorialTable(); + private static readonly double[] DoubleFactorialTable = InitializeDoubleFactorialTable(); + private static readonly double[] SuperFactorialTable = InitializeSuperFactorialTable(); + + private static readonly double[] LanczosCoefficients = + [ + 0.99999999999980993, 676.5203681218851, -1259.1392167224028, + 771.32342877765313, -176.61502916214059, 12.507343278686905, + -0.13857109583111912, 9.9843695780195716e-6, 1.5056327351493116e-7 + ]; + private const double LanczosG = 7.0; + private static readonly double Sqrt2Pi = System.Math.Sqrt(2.0 * System.Math.PI); + + private static double[] InitializeFactorialTable() + { + double[] table = new double[171]; + table[0] = 1.0; + for (int i = 1; i <= 170; i++) + { + table[i] = table[i - 1] * i; + } + return table; + } + + private static double[] InitializeDoubleFactorialTable() + { + double[] table = new double[301]; + table[0] = 1.0; + table[1] = 1.0; + for (int i = 2; i <= 300; i++) + { + table[i] = table[i - 2] * i; + } + return table; + } + + private static double[] InitializeSuperFactorialTable() + { + var list = new List { 1.0 }; // 0$ = 1 + double current = 1.0; + for (int i = 1; i <= 170; i++) + { + double factI = FactorialTable[i]; + if (double.IsInfinity(current) || double.IsInfinity(factI) || current > double.MaxValue / factI) + break; + current *= factI; + list.Add(current); + } + return list.ToArray(); + } + + public static double Factorial(double n) + { + if (double.IsNaN(n)) return double.NaN; + if (double.IsPositiveInfinity(n)) return double.PositiveInfinity; + if (double.IsNegativeInfinity(n)) return double.NaN; + + long intN = (long)System.Math.Round(n); + if (System.Math.Abs(n - intN) < 1e-11) + { + if (intN < 0) return double.NaN; + if (intN <= 170) return FactorialTable[intN]; + return double.PositiveInfinity; + } + + if (n < 0) + { + return Gamma(n + 1.0); + } + + if (n > 171.0) + { + return double.PositiveInfinity; + } + + return Gamma(n + 1.0); + } + + public static double DoubleFactorial(double n) + { + if (double.IsNaN(n)) return double.NaN; + if (double.IsPositiveInfinity(n)) return double.PositiveInfinity; + if (double.IsNegativeInfinity(n)) return double.NaN; + + long intN = (long)System.Math.Round(n); + if (System.Math.Abs(n - intN) < 1e-11) + { + if (intN < -1) return double.NaN; + if (intN == -1) return 1.0; + if (intN <= 300) return DoubleFactorialTable[intN]; + return double.PositiveInfinity; + } + + if (n < -1.0) return double.NaN; + if (n > 301.0) return double.PositiveInfinity; + + // Analytic continuation for real numbers: + // n!! = 2^(n/2) * (2/pi)^((1 - cos(pi*n))/4) * Gamma(n/2 + 1) + double powerTwo = System.Math.Pow(2.0, n / 2.0); + double piFactor = System.Math.Pow(2.0 / System.Math.PI, (1.0 - System.Math.Cos(System.Math.PI * n)) / 4.0); + double gammaVal = Gamma(n / 2.0 + 1.0); + return powerTwo * piFactor * gammaVal; + } + + public static double SuperFactorial(double n) + { + if (double.IsNaN(n)) return double.NaN; + if (double.IsPositiveInfinity(n)) return double.PositiveInfinity; + if (double.IsNegativeInfinity(n)) return double.NaN; + if (n < 0) return double.NaN; + + long intN = (long)System.Math.Round(n); + if (System.Math.Abs(n - intN) < 1e-11) + { + if (intN < SuperFactorialTable.Length) + { + return SuperFactorialTable[intN]; + } + return double.PositiveInfinity; + } + + if (n >= SuperFactorialTable.Length) + { + return double.PositiveInfinity; + } + + long baseN = (long)System.Math.Floor(n); + double frac = n - baseN; + double baseVal = SuperFactorialTable[baseN]; + double currentFact = Factorial(n); + return baseVal * System.Math.Pow(currentFact, frac); + } + + public static double Gamma(double z) + { + if (double.IsNaN(z)) return double.NaN; + if (double.IsPositiveInfinity(z)) return double.PositiveInfinity; + if (double.IsNegativeInfinity(z)) return double.NaN; + + if (z <= 0.0) + { + long intZ = (long)System.Math.Round(z); + if (System.Math.Abs(z - intZ) < 1e-13) + { + return double.NaN; + } + } + + if (z > 171.5) + { + return double.PositiveInfinity; + } + + if (z < 0.5) + { + return System.Math.PI / (System.Math.Sin(System.Math.PI * z) * Gamma(1.0 - z)); + } + + z -= 1.0; + double x = LanczosCoefficients[0]; + for (int i = 1; i < LanczosCoefficients.Length; i++) + { + x += LanczosCoefficients[i] / (z + i); + } + double t = z + LanczosG + 0.5; + return Sqrt2Pi * System.Math.Pow(t, z + 0.5) * System.Math.Exp(-t) * x; + } + public override string ToString() => $"{FunctionName}({string.Join(", ", (IEnumerable)Arguments)})"; } + +public sealed class SumNode : AstNode +{ + public string VariableName { get; } + public AstNode StartExpr { get; } + public AstNode EndExpr { get; } + public AstNode BodyExpr { get; } + + public SumNode(string variableName, AstNode startExpr, AstNode endExpr, AstNode bodyExpr) + { + VariableName = variableName.ToLowerInvariant(); + StartExpr = startExpr; + EndExpr = endExpr; + BodyExpr = bodyExpr; + } + + public override double Evaluate(in EvaluationContext ctx) + { + double startVal = StartExpr.Evaluate(in ctx); + double endVal = EndExpr.Evaluate(in ctx); + + if (double.IsNaN(startVal) || double.IsNaN(endVal) || double.IsInfinity(startVal) || double.IsInfinity(endVal)) + return double.NaN; + + int start = (int)System.Math.Round(startVal); + int end = (int)System.Math.Round(endVal); + + if (start > end) return 0.0; + int maxIter = 5000; + if (end - start > maxIter) end = start + maxIter; + + double sum = 0.0; + for (int i = start; i <= end; i++) + { + var subCtx = ctx.WithScope(VariableName, i); + double term = BodyExpr.Evaluate(in subCtx); + if (double.IsNaN(term)) return double.NaN; + sum += term; + } + return sum; + } + + public override void CollectVariables(HashSet vars) + { + StartExpr.CollectVariables(vars); + EndExpr.CollectVariables(vars); + var bodyVars = new HashSet(StringComparer.OrdinalIgnoreCase); + BodyExpr.CollectVariables(bodyVars); + bodyVars.Remove(VariableName); + foreach (var v in bodyVars) vars.Add(v); + } + + public override string ToString() => $"sum({VariableName}={StartExpr}, {EndExpr}, {BodyExpr})"; +} + +public sealed class ProductNode : AstNode +{ + public string VariableName { get; } + public AstNode StartExpr { get; } + public AstNode EndExpr { get; } + public AstNode BodyExpr { get; } + + public ProductNode(string variableName, AstNode startExpr, AstNode endExpr, AstNode bodyExpr) + { + VariableName = variableName.ToLowerInvariant(); + StartExpr = startExpr; + EndExpr = endExpr; + BodyExpr = bodyExpr; + } + + public override double Evaluate(in EvaluationContext ctx) + { + double startVal = StartExpr.Evaluate(in ctx); + double endVal = EndExpr.Evaluate(in ctx); + + if (double.IsNaN(startVal) || double.IsNaN(endVal) || double.IsInfinity(startVal) || double.IsInfinity(endVal)) + return double.NaN; + + int start = (int)System.Math.Round(startVal); + int end = (int)System.Math.Round(endVal); + + if (start > end) return 1.0; + int maxIter = 1000; + if (end - start > maxIter) end = start + maxIter; + + double prod = 1.0; + for (int i = start; i <= end; i++) + { + var subCtx = ctx.WithScope(VariableName, i); + double factor = BodyExpr.Evaluate(in subCtx); + if (double.IsNaN(factor)) return double.NaN; + prod *= factor; + } + return prod; + } + + public override void CollectVariables(HashSet vars) + { + StartExpr.CollectVariables(vars); + EndExpr.CollectVariables(vars); + var bodyVars = new HashSet(StringComparer.OrdinalIgnoreCase); + BodyExpr.CollectVariables(bodyVars); + bodyVars.Remove(VariableName); + foreach (var v in bodyVars) vars.Add(v); + } + + public override string ToString() => $"prod({VariableName}={StartExpr}, {EndExpr}, {BodyExpr})"; +} + +public sealed class IntegralNode : AstNode +{ + public string VariableName { get; } + public AstNode LowerExpr { get; } + public AstNode UpperExpr { get; } + public AstNode IntegrandExpr { get; } + + public IntegralNode(string variableName, AstNode lowerExpr, AstNode upperExpr, AstNode integrandExpr) + { + VariableName = variableName.ToLowerInvariant(); + LowerExpr = lowerExpr; + UpperExpr = upperExpr; + IntegrandExpr = integrandExpr; + } + + public override double Evaluate(in EvaluationContext ctx) + { + double a = LowerExpr.Evaluate(in ctx); + double b = UpperExpr.Evaluate(in ctx); + + if (double.IsNaN(a) || double.IsNaN(b) || double.IsInfinity(a) || double.IsInfinity(b)) + return double.NaN; + + if (System.Math.Abs(a - b) < 1e-12) return 0.0; + + bool inverted = false; + if (a > b) + { + (a, b) = (b, a); + inverted = true; + } + + int n = 64; // Simpson's rule steps + double h = (b - a) / n; + + var ctxA = ctx.WithScope(VariableName, a); + var ctxB = ctx.WithScope(VariableName, b); + double fa = IntegrandExpr.Evaluate(in ctxA); + double fb = IntegrandExpr.Evaluate(in ctxB); + + if (double.IsNaN(fa) || double.IsNaN(fb) || double.IsInfinity(fa) || double.IsInfinity(fb)) + return double.NaN; + + double sum = fa + fb; + + for (int i = 1; i < n; i++) + { + double t = a + i * h; + var subCtx = ctx.WithScope(VariableName, t); + double val = IntegrandExpr.Evaluate(in subCtx); + if (double.IsNaN(val) || double.IsInfinity(val)) return double.NaN; + + sum += (i % 2 == 1 ? 4.0 : 2.0) * val; + } + + double result = (h / 3.0) * sum; + return inverted ? -result : result; + } + + public override void CollectVariables(HashSet vars) + { + LowerExpr.CollectVariables(vars); + UpperExpr.CollectVariables(vars); + var bodyVars = new HashSet(StringComparer.OrdinalIgnoreCase); + IntegrandExpr.CollectVariables(bodyVars); + bodyVars.Remove(VariableName); + foreach (var v in bodyVars) vars.Add(v); + } + + public override string ToString() => $"int({VariableName}={LowerExpr}, {UpperExpr}, {IntegrandExpr})"; +} + +public sealed class DerivativeNode : AstNode +{ + public string VariableName { get; } + public AstNode AtExpr { get; } + public AstNode BodyExpr { get; } + + public DerivativeNode(string variableName, AstNode atExpr, AstNode bodyExpr) + { + VariableName = variableName.ToLowerInvariant(); + AtExpr = atExpr; + BodyExpr = bodyExpr; + } + + public override double Evaluate(in EvaluationContext ctx) + { + double x0 = AtExpr.Evaluate(in ctx); + if (double.IsNaN(x0) || double.IsInfinity(x0)) return double.NaN; + + double h = 1e-5; + var ctxPlus = ctx.WithScope(VariableName, x0 + h); + var ctxMinus = ctx.WithScope(VariableName, x0 - h); + + double yPlus = BodyExpr.Evaluate(in ctxPlus); + double yMinus = BodyExpr.Evaluate(in ctxMinus); + + if (double.IsNaN(yPlus) || double.IsNaN(yMinus) || double.IsInfinity(yPlus) || double.IsInfinity(yMinus)) + return double.NaN; + + return (yPlus - yMinus) / (2.0 * h); + } + + public override void CollectVariables(HashSet vars) + { + AtExpr.CollectVariables(vars); + var bodyVars = new HashSet(StringComparer.OrdinalIgnoreCase); + BodyExpr.CollectVariables(bodyVars); + bodyVars.Remove(VariableName); + foreach (var v in bodyVars) vars.Add(v); + } + + public override string ToString() => $"diff({VariableName}={AtExpr}, {BodyExpr})"; +} + +public sealed class FactorialNode : AstNode +{ + public AstNode Operand { get; } + public FactorialNode(AstNode operand) => Operand = operand; + public override double Evaluate(in EvaluationContext ctx) => FunctionCallNode.Factorial(Operand.Evaluate(in ctx)); + public override void CollectVariables(HashSet vars) => Operand.CollectVariables(vars); + public override string ToString() => $"({Operand})!"; +} + +public sealed class DoubleFactorialNode : AstNode +{ + public AstNode Operand { get; } + public DoubleFactorialNode(AstNode operand) => Operand = operand; + public override double Evaluate(in EvaluationContext ctx) => FunctionCallNode.DoubleFactorial(Operand.Evaluate(in ctx)); + public override void CollectVariables(HashSet vars) => Operand.CollectVariables(vars); + public override string ToString() => $"({Operand})!!"; +} + +public sealed class SuperFactorialNode : AstNode +{ + public AstNode Operand { get; } + public SuperFactorialNode(AstNode operand) => Operand = operand; + public override double Evaluate(in EvaluationContext ctx) => FunctionCallNode.SuperFactorial(Operand.Evaluate(in ctx)); + public override void CollectVariables(HashSet vars) => Operand.CollectVariables(vars); + public override string ToString() => $"({Operand})$"; +} diff --git a/src/GraphTUI/Core/Math/Evaluator.cs b/src/GraphTUI/Core/Math/Evaluator.cs index 5844fd9..f116900 100644 --- a/src/GraphTUI/Core/Math/Evaluator.cs +++ b/src/GraphTUI/Core/Math/Evaluator.cs @@ -23,6 +23,30 @@ public sealed class Evaluator return Root.Evaluate(in ctx); } + public double Evaluate(double x, double y, Func? parameterLookup = null) + { + var ctx = new EvaluationContext(x: x, y: y, parameterLookup: parameterLookup); + return Root.Evaluate(in ctx); + } + + public double EvaluateY(double y, Func? parameterLookup = null) + { + var ctx = new EvaluationContext(y: y, parameterLookup: parameterLookup); + return Root.Evaluate(in ctx); + } + + public HashSet GetVariables() + { + var vars = new HashSet(StringComparer.OrdinalIgnoreCase); + Root.CollectVariables(vars); + return vars; + } + + public bool ContainsVariable(string varName) + { + return GetVariables().Contains(varName); + } + public double EvaluateParametricX(double t, Func? parameterLookup = null) { var ctx = new EvaluationContext(t: t, parameterLookup: parameterLookup); @@ -43,7 +67,7 @@ public sealed class Evaluator public double EvaluateFull(double x, double t, double theta, Func? parameterLookup = null) { - var ctx = new EvaluationContext(x, t, theta, parameterLookup); + var ctx = new EvaluationContext(x: x, t: t, theta: theta, parameterLookup: parameterLookup); return Root.Evaluate(in ctx); } } diff --git a/src/GraphTUI/Core/Math/Lexer.cs b/src/GraphTUI/Core/Math/Lexer.cs index 81978b3..05dbabe 100644 --- a/src/GraphTUI/Core/Math/Lexer.cs +++ b/src/GraphTUI/Core/Math/Lexer.cs @@ -11,7 +11,9 @@ public sealed class Lexer "sinh", "cosh", "tanh", "exp", "ln", "log", "log2", "log10", "sqrt", "cbrt", "abs", "floor", "ceil", "round", "sgn", "sign", - "min", "max", "clamp" + "min", "max", "clamp", + "sum", "prod", "int", "integral", "diff", "deriv", "derivative", "fact", "gamma", + "dfact", "doublefact", "sfact", "superfact" }; private readonly string _input; @@ -47,6 +49,24 @@ public sealed class Lexer { rawTokens.Add(ReadIdentifier()); } + else if (ch == '!') + { + _pos++; + if (_pos < _input.Length && _input[_pos] == '!') + { + _pos++; + rawTokens.Add(new Token(TokenType.DoubleFactorial, "!!", 0, start)); + } + else + { + rawTokens.Add(new Token(TokenType.Factorial, "!", 0, start)); + } + } + else if (ch == '$') + { + _pos++; + rawTokens.Add(new Token(TokenType.SuperFactorial, "$", 0, start)); + } else { _pos++; @@ -61,6 +81,7 @@ public sealed class Lexer '(' => TokenType.LParen, ')' => TokenType.RParen, ',' => TokenType.Comma, + '=' => TokenType.Equals, _ => throw new FormatException($"Unexpected character '{ch}' at position {start}") }; rawTokens.Add(new Token(type, ch.ToString(), 0, start)); @@ -159,6 +180,9 @@ public sealed class Lexer { TokenType.Number => true, TokenType.RParen => true, + TokenType.Factorial => true, + TokenType.DoubleFactorial => true, + TokenType.SuperFactorial => true, TokenType.Identifier => !KnownFunctions.Contains(curr.Text) || next.Type != TokenType.LParen, _ => false }; @@ -167,7 +191,7 @@ public sealed class Lexer { TokenType.Identifier => true, TokenType.LParen => true, - TokenType.Number => curr.Type == TokenType.RParen, // e.g. (x+1)2 -> (x+1)*2 + TokenType.Number => curr.Type is TokenType.RParen or TokenType.Factorial or TokenType.DoubleFactorial or TokenType.SuperFactorial, _ => false }; diff --git a/src/GraphTUI/Core/Math/Parser.cs b/src/GraphTUI/Core/Math/Parser.cs index 30174ad..792782f 100644 --- a/src/GraphTUI/Core/Math/Parser.cs +++ b/src/GraphTUI/Core/Math/Parser.cs @@ -98,6 +98,33 @@ public sealed class Parser } private AstNode ParsePrimary() + { + var node = ParseAtom(); + + while (true) + { + if (Match(TokenType.DoubleFactorial)) + { + node = new DoubleFactorialNode(node); + } + else if (Match(TokenType.Factorial)) + { + node = new FactorialNode(node); + } + else if (Match(TokenType.SuperFactorial)) + { + node = new SuperFactorialNode(node); + } + else + { + break; + } + } + + return node; + } + + private AstNode ParseAtom() { var token = Current; @@ -114,6 +141,32 @@ public sealed class Parser // Check if it's a function call if (Match(TokenType.LParen)) { + string lowerName = name.ToLowerInvariant(); + + // 1. Summation: sum(n=start, end, f(n)) or sum(n, start, end, f(n)) + if (lowerName == "sum") + { + return ParseSum(); + } + + // 2. Product notation: prod(n=start, end, f(n)) or prod(n, start, end, f(n)) + if (lowerName == "prod") + { + return ParseProduct(); + } + + // 3. Definite Integral: int(t=a, b, f(t)) or integral(t=a, b, f(t)) + if (lowerName is "int" or "integral") + { + return ParseIntegral(); + } + + // 4. Numerical Derivative: diff(t=x, f(t)) or diff(f(x), x) + if (lowerName is "diff" or "deriv" or "derivative") + { + return ParseDerivative(); + } + var args = new List(); if (Current.Type != TokenType.RParen) { @@ -145,6 +198,118 @@ public sealed class Parser throw new FormatException($"Unexpected token '{token.Text}' at position {token.Position}"); } + private AstNode ParseSum() + { + string varName = "n"; + if (Current.Type == TokenType.Identifier) + { + varName = Current.Text; + _pos++; + + if (!Match(TokenType.Equals) && !Match(TokenType.Comma)) + { + throw new FormatException($"Expected '=' or ',' after loop variable in sum at position {Current.Position}"); + } + } + + var start = ParseBinary(0); + Expect(TokenType.Comma, "Expected ',' after start bound in sum."); + var end = ParseBinary(0); + Expect(TokenType.Comma, "Expected ',' after end bound in sum."); + var body = ParseBinary(0); + Expect(TokenType.RParen, "Expected ')' after sum expression."); + + return new SumNode(varName, start, end, body); + } + + private AstNode ParseProduct() + { + string varName = "n"; + if (Current.Type == TokenType.Identifier) + { + varName = Current.Text; + _pos++; + + if (!Match(TokenType.Equals) && !Match(TokenType.Comma)) + { + throw new FormatException($"Expected '=' or ',' after loop variable in prod at position {Current.Position}"); + } + } + + var start = ParseBinary(0); + Expect(TokenType.Comma, "Expected ',' after start bound in prod."); + var end = ParseBinary(0); + Expect(TokenType.Comma, "Expected ',' after end bound in prod."); + var body = ParseBinary(0); + Expect(TokenType.RParen, "Expected ')' after prod expression."); + + return new ProductNode(varName, start, end, body); + } + + private AstNode ParseIntegral() + { + string varName = "t"; + if (Current.Type == TokenType.Identifier) + { + varName = Current.Text; + _pos++; + + if (!Match(TokenType.Equals) && !Match(TokenType.Comma)) + { + throw new FormatException($"Expected '=' or ',' after variable in integral at position {Current.Position}"); + } + } + + var lower = ParseBinary(0); + Expect(TokenType.Comma, "Expected ',' after lower bound in integral."); + var upper = ParseBinary(0); + Expect(TokenType.Comma, "Expected ',' after upper bound in integral."); + var integrand = ParseBinary(0); + Expect(TokenType.RParen, "Expected ')' after integral expression."); + + return new IntegralNode(varName, lower, upper, integrand); + } + + private AstNode ParseDerivative() + { + // Check if syntax is: diff(t=x, f(t)) or diff(t, x, f(t)) + if (Current.Type == TokenType.Identifier && _pos + 1 < _tokens.Count && + (_tokens[_pos + 1].Type == TokenType.Equals || _tokens[_pos + 1].Type == TokenType.Comma)) + { + string varName = Current.Text; + _pos++; + + bool hadEquals = Match(TokenType.Equals); + bool hadComma = !hadEquals && Match(TokenType.Comma); + + var firstExpr = ParseBinary(0); + + if (Match(TokenType.Comma)) + { + // diff(t, x, f(t)) or diff(t=x, f(t)) + var body = ParseBinary(0); + Expect(TokenType.RParen, "Expected ')' after derivative expression."); + return new DerivativeNode(varName, firstExpr, body); + } + else + { + // diff(var, expr) where evaluation point defaults to var + Expect(TokenType.RParen, "Expected ')' after derivative expression."); + return new DerivativeNode(varName, new VariableNode(varName), firstExpr); + } + } + else + { + // diff(f(x), x) + var body = ParseBinary(0); + Expect(TokenType.Comma, "Expected ',' after expression in diff."); + string varName = Current.Text; + Expect(TokenType.Identifier, "Expected variable name in diff."); + Expect(TokenType.RParen, "Expected ')' after diff."); + return new DerivativeNode(varName, new VariableNode(varName), body); + } + } + private Token Current => _pos < _tokens.Count ? _tokens[_pos] : _tokens[^1]; private bool Match(TokenType type) diff --git a/src/GraphTUI/Core/Math/Token.cs b/src/GraphTUI/Core/Math/Token.cs index a43c5fe..6e38132 100644 --- a/src/GraphTUI/Core/Math/Token.cs +++ b/src/GraphTUI/Core/Math/Token.cs @@ -13,6 +13,10 @@ public enum TokenType LParen, RParen, Comma, + Equals, + Factorial, // ! + DoubleFactorial, // !! + SuperFactorial, // $ Eof } diff --git a/src/GraphTUI/Core/Models/FunctionType.cs b/src/GraphTUI/Core/Models/FunctionType.cs index 8216b6c..59b8561 100644 --- a/src/GraphTUI/Core/Models/FunctionType.cs +++ b/src/GraphTUI/Core/Models/FunctionType.cs @@ -3,6 +3,8 @@ namespace GraphTUI.Core.Models; public enum FunctionType { Cartesian, // y = f(x) + CartesianX, // x = f(y) or f(y) = x + Implicit, // f(y) = g(x) or F(x, y) = 0 Parametric, // x = x(t), y = y(t) Polar // r = f(theta) } diff --git a/src/GraphTUI/Core/Models/GraphFunction.cs b/src/GraphTUI/Core/Models/GraphFunction.cs index 0eef851..9542288 100644 --- a/src/GraphTUI/Core/Models/GraphFunction.cs +++ b/src/GraphTUI/Core/Models/GraphFunction.cs @@ -28,6 +28,8 @@ public sealed class GraphFunction // Compiled evaluators & error states public Evaluator? Evaluator { get; private set; } public Evaluator? EvaluatorY { get; private set; } + public Evaluator? EvaluatorLhs { get; private set; } + public Evaluator? EvaluatorRhs { get; private set; } public string? CompilationError { get; private set; } public GraphFunction(int id, string expression, ColorRgb color, FunctionType type = FunctionType.Cartesian, string parametricY = "") @@ -50,6 +52,8 @@ public sealed class GraphFunction CompilationError = null; Evaluator = null; EvaluatorY = null; + EvaluatorLhs = null; + EvaluatorRhs = null; if (string.IsNullOrWhiteSpace(Expression)) { @@ -57,32 +61,129 @@ public sealed class GraphFunction return; } - try - { - Evaluator = Evaluator.Compile(Expression); - } - catch (Exception ex) - { - CompilationError = ex.Message; - return; - } - + // Parametric mode if (Type == FunctionType.Parametric) { - if (string.IsNullOrWhiteSpace(ParametricY)) - { - CompilationError = "Parametric Y expression is empty"; - return; - } - try { + Evaluator = Evaluator.Compile(Expression); + if (string.IsNullOrWhiteSpace(ParametricY)) + { + CompilationError = "Parametric Y expression is empty"; + return; + } EvaluatorY = Evaluator.Compile(ParametricY); } catch (Exception ex) { CompilationError = ex.Message; } + return; + } + + // Polar mode + if (Type == FunctionType.Polar) + { + try + { + string polarExpr = Expression; + if (polarExpr.Contains('=')) + { + var eqParts = polarExpr.Split('=', 2); + polarExpr = eqParts[1].Trim(); + } + Evaluator = Evaluator.Compile(polarExpr); + } + catch (Exception ex) + { + CompilationError = ex.Message; + } + return; + } + + // Cartesian / CartesianX / Implicit modes (auto-classified or double-sided) + try + { + if (Expression.Contains('=')) + { + var parts = Expression.Split('=', 2); + string leftStr = parts[0].Trim(); + string rightStr = parts[1].Trim(); + + var leftEval = Evaluator.Compile(leftStr); + var rightEval = Evaluator.Compile(rightStr); + + bool leftIsY = leftStr.Equals("y", StringComparison.OrdinalIgnoreCase); + bool rightIsY = rightStr.Equals("y", StringComparison.OrdinalIgnoreCase); + bool leftIsX = leftStr.Equals("x", StringComparison.OrdinalIgnoreCase); + bool rightIsX = rightStr.Equals("x", StringComparison.OrdinalIgnoreCase); + + bool leftHasX = leftEval.ContainsVariable("x"); + bool leftHasY = leftEval.ContainsVariable("y"); + bool rightHasX = rightEval.ContainsVariable("x"); + bool rightHasY = rightEval.ContainsVariable("y"); + + // Case 1: y = f(x) or f(x) = y + if (leftIsY && !rightHasY) + { + Type = FunctionType.Cartesian; + Evaluator = rightEval; + } + else if (rightIsY && !leftHasY) + { + Type = FunctionType.Cartesian; + Evaluator = leftEval; + } + // Case 2: x = f(y) or f(y) = x + else if (leftIsX && !rightHasX) + { + Type = FunctionType.CartesianX; + Evaluator = rightEval; + } + else if (rightIsX && !leftHasX) + { + Type = FunctionType.CartesianX; + Evaluator = leftEval; + } + // Case 3: Double-sided f(y) = g(x) or general implicit F(x, y) = 0 + else + { + Type = FunctionType.Implicit; + EvaluatorLhs = leftEval; + EvaluatorRhs = rightEval; + } + } + else + { + // No '=' present + var eval = Evaluator.Compile(Expression); + bool hasX = eval.ContainsVariable("x"); + bool hasY = eval.ContainsVariable("y"); + + if (hasY && !hasX) + { + // f(y) without x -> x = f(y) + Type = FunctionType.CartesianX; + Evaluator = eval; + } + else if (hasX && hasY) + { + // F(x, y) without = -> F(x, y) = 0 + Type = FunctionType.Implicit; + EvaluatorLhs = eval; + EvaluatorRhs = Evaluator.Compile("0"); + } + else + { + // Default to y = f(x) + Type = FunctionType.Cartesian; + Evaluator = eval; + } + } + } + catch (Exception ex) + { + CompilationError = ex.Message; } } @@ -90,9 +191,11 @@ public sealed class GraphFunction { return Type switch { - FunctionType.Cartesian => $"y = {Expression}", + FunctionType.Cartesian => Expression.Contains('=') ? Expression : $"y = {Expression}", + FunctionType.CartesianX => Expression.Contains('=') ? Expression : $"x = {Expression}", + FunctionType.Implicit => Expression.Contains('=') ? Expression : $"{Expression} = 0", FunctionType.Parametric => $"x(t)={Expression}, y(t)={ParametricY}", - FunctionType.Polar => $"r = {Expression}", + FunctionType.Polar => Expression.Contains('=') ? Expression : $"r = {Expression}", _ => Expression }; } diff --git a/src/GraphTUI/Core/Models/Viewport.cs b/src/GraphTUI/Core/Models/Viewport.cs index 96b5d76..69ad255 100644 --- a/src/GraphTUI/Core/Models/Viewport.cs +++ b/src/GraphTUI/Core/Models/Viewport.cs @@ -69,9 +69,20 @@ public sealed class Viewport if (subWidth <= 1) subWidth = 2; if (subHeight <= 1) subHeight = 2; + if (double.IsNaN(x) || double.IsInfinity(x) || double.IsNaN(y) || double.IsInfinity(y)) + { + subX = 0; + subY = 0; + return false; + } + double normX = (x - XMin) / Width; double normY = (YMax - y) / Height; // top is 0 + // Clamp normalized coordinates to a safe range to prevent 32-bit integer overflow + normX = System.Math.Clamp(normX, -10000.0, 10000.0); + normY = System.Math.Clamp(normY, -10000.0, 10000.0); + subX = (int)System.Math.Round(normX * (subWidth - 1)); subY = (int)System.Math.Round(normY * (subHeight - 1)); @@ -92,9 +103,19 @@ public sealed class Viewport if (viewCols <= 1) viewCols = 2; if (viewRows <= 1) viewRows = 2; + if (double.IsNaN(x) || double.IsInfinity(x) || double.IsNaN(y) || double.IsInfinity(y)) + { + col = 0; + row = 0; + return false; + } + double normX = (x - XMin) / Width; double normY = (YMax - y) / Height; + normX = System.Math.Clamp(normX, -10000.0, 10000.0); + normY = System.Math.Clamp(normY, -10000.0, 10000.0); + col = (int)System.Math.Round(normX * (viewCols - 1)); row = (int)System.Math.Round(normY * (viewRows - 1)); diff --git a/src/GraphTUI/Rendering/BrailleCanvas.cs b/src/GraphTUI/Rendering/BrailleCanvas.cs index a3d5629..0b13935 100644 --- a/src/GraphTUI/Rendering/BrailleCanvas.cs +++ b/src/GraphTUI/Rendering/BrailleCanvas.cs @@ -74,32 +74,118 @@ public sealed class BrailleCanvas _bgColors[cellRow * CellWidth + cellCol] = color; } - public void DrawLine(int x0, int y0, int x1, int y1, ColorRgb color) + private const int CLIP_INSIDE = 0; + private const int CLIP_LEFT = 1; + private const int CLIP_RIGHT = 2; + private const int CLIP_BOTTOM = 4; + private const int CLIP_TOP = 8; + + private static int ComputeOutCode(double x, double y, double xmin, double ymin, double xmax, double ymax) { - // Bresenham's line algorithm on subpixel grid - int dx = System.Math.Abs(x1 - x0); - int dy = System.Math.Abs(y1 - y0); - int sx = x0 < x1 ? 1 : -1; - int sy = y0 < y1 ? 1 : -1; + int code = CLIP_INSIDE; + if (x < xmin) code |= CLIP_LEFT; + else if (x > xmax) code |= CLIP_RIGHT; + if (y < ymin) code |= CLIP_TOP; + else if (y > ymax) code |= CLIP_BOTTOM; + return code; + } + + public void DrawLine(int x0Int, int y0Int, int x1Int, int y1Int, ColorRgb color) + { + double xmin = 0; + double ymin = 0; + double xmax = SubpixelWidth - 1; + double ymax = SubpixelHeight - 1; + + double x0 = x0Int; + double y0 = y0Int; + double x1 = x1Int; + double y1 = y1Int; + + int code0 = ComputeOutCode(x0, y0, xmin, ymin, xmax, ymax); + int code1 = ComputeOutCode(x1, y1, xmin, ymin, xmax, ymax); + bool accept = false; + + for (int iter = 0; iter < 4; iter++) + { + if ((code0 | code1) == 0) + { + accept = true; + break; + } + if ((code0 & code1) != 0) + { + break; + } + + int outcode = code0 != 0 ? code0 : code1; + double x = 0, y = 0; + + if ((outcode & CLIP_TOP) != 0) + { + x = x0 + (x1 - x0) * (ymin - y0) / (y1 - y0); + y = ymin; + } + else if ((outcode & CLIP_BOTTOM) != 0) + { + x = x0 + (x1 - x0) * (ymax - y0) / (y1 - y0); + y = ymax; + } + else if ((outcode & CLIP_RIGHT) != 0) + { + y = y0 + (y1 - y0) * (xmax - x0) / (x1 - x0); + x = xmax; + } + else if ((outcode & CLIP_LEFT) != 0) + { + y = y0 + (y1 - y0) * (xmin - x0) / (x1 - x0); + x = xmin; + } + + if (outcode == code0) + { + x0 = x; + y0 = y; + code0 = ComputeOutCode(x0, y0, xmin, ymin, xmax, ymax); + } + else + { + x1 = x; + y1 = y; + code1 = ComputeOutCode(x1, y1, xmin, ymin, xmax, ymax); + } + } + + if (!accept) return; + + int cx0 = System.Math.Clamp((int)System.Math.Round(x0), 0, SubpixelWidth - 1); + int cy0 = System.Math.Clamp((int)System.Math.Round(y0), 0, SubpixelHeight - 1); + int cx1 = System.Math.Clamp((int)System.Math.Round(x1), 0, SubpixelWidth - 1); + int cy1 = System.Math.Clamp((int)System.Math.Round(y1), 0, SubpixelHeight - 1); + + int dx = System.Math.Abs(cx1 - cx0); + int dy = System.Math.Abs(cy1 - cy0); + int sx = cx0 < cx1 ? 1 : -1; + int sy = cy0 < cy1 ? 1 : -1; int err = dx - dy; while (true) { - SetPixel(x0, y0, color); + SetPixel(cx0, cy0, color); - if (x0 == x1 && y0 == y1) + if (cx0 == cx1 && cy0 == cy1) break; int e2 = 2 * err; if (e2 > -dy) { err -= dy; - x0 += sx; + cx0 += sx; } if (e2 < dx) { err += dx; - y0 += sy; + cy0 += sy; } } } diff --git a/src/GraphTUI/Rendering/PlotRenderer.cs b/src/GraphTUI/Rendering/PlotRenderer.cs index 7c85805..a12fd60 100644 --- a/src/GraphTUI/Rendering/PlotRenderer.cs +++ b/src/GraphTUI/Rendering/PlotRenderer.cs @@ -174,6 +174,12 @@ public sealed class PlotRenderer case FunctionType.Cartesian: RenderCartesian(canvas, viewport, fn, paramLookup, crosshairX); break; + case FunctionType.CartesianX: + RenderCartesianX(canvas, viewport, fn, paramLookup); + break; + case FunctionType.Implicit: + RenderImplicit(canvas, viewport, fn, paramLookup); + break; case FunctionType.Parametric: RenderParametric(canvas, viewport, fn, paramLookup); break; @@ -323,6 +329,223 @@ public sealed class PlotRenderer } } + private static void RenderCartesianX( + BrailleCanvas canvas, + Viewport viewport, + GraphFunction fn, + Func? paramLookup) + { + if (fn.Evaluator == null) return; + + int subW = canvas.SubpixelWidth; + int subH = canvas.SubpixelHeight; + + int? lastSx = null; + int? lastSy = null; + double lastX = double.NaN; + + for (int sy = 0; sy < subH; sy++) + { + viewport.SubpixelToMath(0, sy, subW, subH, out _, out double y); + double x = fn.Evaluator.EvaluateY(y, paramLookup); + + if (double.IsNaN(x) || double.IsInfinity(x)) + { + lastSx = null; + lastSy = null; + lastX = double.NaN; + continue; + } + + viewport.MathToSubpixel(x, y, subW, subH, out int sx, out _); + + if (lastSx.HasValue && lastSy.HasValue) + { + bool isAsymptote = !double.IsNaN(lastX) && + (x * lastX < 0) && + (System.Math.Abs(sx - lastSx.Value) > subW / 2); + + if (!isAsymptote) + { + canvas.DrawLine(lastSx.Value, lastSy.Value, sx, sy, fn.Color); + } + else + { + canvas.SetPixel(sx, sy, fn.Color); + } + } + else + { + canvas.SetPixel(sx, sy, fn.Color); + } + + lastSx = sx; + lastSy = sy; + lastX = x; + } + } + + private static void RenderImplicit( + BrailleCanvas canvas, + Viewport viewport, + GraphFunction fn, + Func? paramLookup) + { + if (fn.EvaluatorLhs == null || fn.EvaluatorRhs == null) return; + + int subW = canvas.SubpixelWidth; + int subH = canvas.SubpixelHeight; + + bool lhsOnlyY = fn.EvaluatorLhs.ContainsVariable("y") && !fn.EvaluatorLhs.ContainsVariable("x"); + bool rhsOnlyX = fn.EvaluatorRhs.ContainsVariable("x") && !fn.EvaluatorRhs.ContainsVariable("y"); + + bool lhsOnlyX = fn.EvaluatorLhs.ContainsVariable("x") && !fn.EvaluatorLhs.ContainsVariable("y"); + bool rhsOnlyY = fn.EvaluatorRhs.ContainsVariable("y") && !fn.EvaluatorRhs.ContainsVariable("x"); + + // Fast path for f(y) = g(x) or g(x) = f(y): 1D precomputations + double[]? precomputedLhsY = null; + double[]? precomputedRhsX = null; + double[]? precomputedLhsX = null; + double[]? precomputedRhsY = null; + + if (lhsOnlyY && rhsOnlyX) + { + precomputedLhsY = new double[subH + 1]; + for (int sy = 0; sy <= subH; sy++) + { + viewport.SubpixelToMath(0, sy, subW, subH, out _, out double y); + precomputedLhsY[sy] = fn.EvaluatorLhs.EvaluateY(y, paramLookup); + } + + precomputedRhsX = new double[subW + 1]; + for (int sx = 0; sx <= subW; sx++) + { + viewport.SubpixelToMath(sx, 0, subW, subH, out double x, out _); + precomputedRhsX[sx] = fn.EvaluatorRhs.Evaluate(x, paramLookup); + } + } + else if (lhsOnlyX && rhsOnlyY) + { + precomputedLhsX = new double[subW + 1]; + for (int sx = 0; sx <= subW; sx++) + { + viewport.SubpixelToMath(sx, 0, subW, subH, out double x, out _); + precomputedLhsX[sx] = fn.EvaluatorLhs.Evaluate(x, paramLookup); + } + + precomputedRhsY = new double[subH + 1]; + for (int sy = 0; sy <= subH; sy++) + { + viewport.SubpixelToMath(0, sy, subW, subH, out _, out double y); + precomputedRhsY[sy] = fn.EvaluatorRhs.EvaluateY(y, paramLookup); + } + } + + double EvalV(int sx, int sy) + { + if (precomputedLhsY != null && precomputedRhsX != null) + { + double l = precomputedLhsY[sy]; + double r = precomputedRhsX[sx]; + return l - r; + } + if (precomputedLhsX != null && precomputedRhsY != null) + { + double l = precomputedLhsX[sx]; + double r = precomputedRhsY[sy]; + return l - r; + } + + viewport.SubpixelToMath(sx, sy, subW, subH, out double xVal, out double yVal); + double lhs = fn.EvaluatorLhs.Evaluate(xVal, yVal, paramLookup); + double rhs = fn.EvaluatorRhs.Evaluate(xVal, yVal, paramLookup); + return lhs - rhs; + } + + double[] prevRow = new double[subW + 1]; + double[] currRow = new double[subW + 1]; + + for (int sx = 0; sx <= subW; sx++) + { + prevRow[sx] = EvalV(sx, 0); + } + + for (int sy = 0; sy < subH; sy++) + { + for (int sx = 0; sx <= subW; sx++) + { + currRow[sx] = EvalV(sx, sy + 1); + } + + for (int sx = 0; sx < subW; sx++) + { + double cTL = prevRow[sx]; + double cTR = prevRow[sx + 1]; + double cBL = currRow[sx]; + double cBR = currRow[sx + 1]; + + if (double.IsNaN(cTL) || double.IsNaN(cTR) || double.IsNaN(cBL) || double.IsNaN(cBR) || + double.IsInfinity(cTL) || double.IsInfinity(cTR) || double.IsInfinity(cBL) || double.IsInfinity(cBR)) + { + continue; + } + + var crossings = new List<(int X, int Y)>(4); + + // Top edge + if (cTL * cTR <= 0 && System.Math.Abs(cTL - cTR) < 1e5) + { + double t = System.Math.Abs(cTL) / (System.Math.Abs(cTL) + System.Math.Abs(cTR) + 1e-12); + int px = (int)System.Math.Round(sx + t); + crossings.Add((px, sy)); + } + + // Bottom edge + if (cBL * cBR <= 0 && System.Math.Abs(cBL - cBR) < 1e5) + { + double t = System.Math.Abs(cBL) / (System.Math.Abs(cBL) + System.Math.Abs(cBR) + 1e-12); + int px = (int)System.Math.Round(sx + t); + crossings.Add((px, sy + 1)); + } + + // Left edge + if (cTL * cBL <= 0 && System.Math.Abs(cTL - cBL) < 1e5) + { + double t = System.Math.Abs(cTL) / (System.Math.Abs(cTL) + System.Math.Abs(cBL) + 1e-12); + int py = (int)System.Math.Round(sy + t); + crossings.Add((sx, py)); + } + + // Right edge + if (cTR * cBR <= 0 && System.Math.Abs(cTR - cBR) < 1e5) + { + double t = System.Math.Abs(cTR) / (System.Math.Abs(cTR) + System.Math.Abs(cBR) + 1e-12); + int py = (int)System.Math.Round(sy + t); + crossings.Add((sx + 1, py)); + } + + if (crossings.Count == 1) + { + canvas.SetPixel(crossings[0].X, crossings[0].Y, fn.Color); + } + else if (crossings.Count == 2) + { + canvas.DrawLine(crossings[0].X, crossings[0].Y, crossings[1].X, crossings[1].Y, fn.Color); + } + else if (crossings.Count > 2) + { + canvas.DrawLine(crossings[0].X, crossings[0].Y, crossings[1].X, crossings[1].Y, fn.Color); + if (crossings.Count >= 4) + { + canvas.DrawLine(crossings[2].X, crossings[2].Y, crossings[3].X, crossings[3].Y, fn.Color); + } + } + } + + (prevRow, currRow) = (currRow, prevRow); + } + } + private static void RenderParametric( BrailleCanvas canvas, Viewport viewport, diff --git a/src/GraphTUI/Rendering/SvgExporter.cs b/src/GraphTUI/Rendering/SvgExporter.cs index 162bf08..34e63a2 100644 --- a/src/GraphTUI/Rendering/SvgExporter.cs +++ b/src/GraphTUI/Rendering/SvgExporter.cs @@ -15,7 +15,7 @@ public static class SvgExporter { var sb = new StringBuilder(); sb.AppendLine($""); - sb.AppendLine($" "); + sb.AppendLine(" "); // Helper to convert math (x, y) to svg (sx, sy) (double sx, double sy) ToSvg(double x, double y) @@ -62,8 +62,6 @@ public static class SvgExporter } var (sx, sy) = ToSvg(x, y); - - // Clamp excessively large coordinates in SVG sy = System.Math.Clamp(sy, -height, height * 2); if (isFirst) @@ -78,6 +76,103 @@ public static class SvgExporter } sb.AppendLine("\" />"); } + else if (fn.Type == FunctionType.CartesianX && fn.Evaluator != null) + { + sb.AppendLine(CultureInfo.InvariantCulture, $" "); + } + else if (fn.Type == FunctionType.Implicit && fn.EvaluatorLhs != null && fn.EvaluatorRhs != null) + { + sb.AppendLine(CultureInfo.InvariantCulture, $" (4); + if (cTL * cTR <= 0 && System.Math.Abs(cTL - cTR) < 1e5) + { + double t = System.Math.Abs(cTL) / (System.Math.Abs(cTL) + System.Math.Abs(cTR) + 1e-12); + crossings.Add(((gx + t) / gridW * width, (double)gy / gridH * height)); + } + if (cBL * cBR <= 0 && System.Math.Abs(cBL - cBR) < 1e5) + { + double t = System.Math.Abs(cBL) / (System.Math.Abs(cBL) + System.Math.Abs(cBR) + 1e-12); + crossings.Add(((gx + t) / gridW * width, (double)(gy + 1) / gridH * height)); + } + if (cTL * cBL <= 0 && System.Math.Abs(cTL - cBL) < 1e5) + { + double t = System.Math.Abs(cTL) / (System.Math.Abs(cTL) + System.Math.Abs(cBL) + 1e-12); + crossings.Add(((double)gx / gridW * width, (gy + t) / gridH * height)); + } + if (cTR * cBR <= 0 && System.Math.Abs(cTR - cBR) < 1e5) + { + double t = System.Math.Abs(cTR) / (System.Math.Abs(cTR) + System.Math.Abs(cBR) + 1e-12); + crossings.Add(((double)(gx + 1) / gridW * width, (gy + t) / gridH * height)); + } + + if (crossings.Count >= 2) + { + sb.Append(CultureInfo.InvariantCulture, $" M {crossings[0].X:F1} {crossings[0].Y:F1} L {crossings[1].X:F1} {crossings[1].Y:F1}"); + } + } + + (prevRow, currRow) = (currRow, prevRow); + } + + sb.AppendLine("\" />"); + } else if (fn.Type == FunctionType.Parametric && fn.Evaluator != null && fn.EvaluatorY != null) { sb.AppendLine(CultureInfo.InvariantCulture, $" new KeyAction(KeyCode.F2, Shift: shift, Ctrl: ctrl, Alt: alt), ConsoleKey.F3 => new KeyAction(KeyCode.F3, Shift: shift, Ctrl: ctrl, Alt: alt), ConsoleKey.F4 => new KeyAction(KeyCode.F4, Shift: shift, Ctrl: ctrl, Alt: alt), + ConsoleKey.F5 => new KeyAction(KeyCode.F5, Shift: shift, Ctrl: ctrl, Alt: alt), _ => new KeyAction(KeyCode.Char, info.KeyChar, Shift: shift, Ctrl: ctrl, Alt: alt) }; } @@ -102,6 +103,7 @@ public sealed class InputReader "OQ" or "[12~" => new KeyAction(KeyCode.F2), "OR" or "[13~" => new KeyAction(KeyCode.F3), "OS" or "[14~" => new KeyAction(KeyCode.F4), + "[15~" => new KeyAction(KeyCode.F5), _ => null }; } diff --git a/src/GraphTUI/Terminal/KeyAction.cs b/src/GraphTUI/Terminal/KeyAction.cs index 4d0ae4b..1c9a058 100644 --- a/src/GraphTUI/Terminal/KeyAction.cs +++ b/src/GraphTUI/Terminal/KeyAction.cs @@ -20,7 +20,8 @@ public enum KeyCode F1, F2, F3, - F4 + F4, + F5 } public readonly record struct KeyAction(KeyCode Code, char KeyChar = '\0', bool Shift = false, bool Ctrl = false, bool Alt = false); diff --git a/src/GraphTUI/UI/Views/CheatsheetModal.cs b/src/GraphTUI/UI/Views/CheatsheetModal.cs new file mode 100644 index 0000000..b76e1a8 --- /dev/null +++ b/src/GraphTUI/UI/Views/CheatsheetModal.cs @@ -0,0 +1,262 @@ +using GraphTUI.Rendering; +using GraphTUI.Terminal; + +namespace GraphTUI.UI.Views; + +public sealed class CheatsheetCategory +{ + public string Title { get; } + public (string Syntax, string Description, string Example)[] Entries { get; } + + public CheatsheetCategory(string title, (string Syntax, string Description, string Example)[] entries) + { + Title = title; + Entries = entries; + } +} + +public sealed class CheatsheetModal +{ + public bool IsOpen { get; set; } = false; + public int SelectedCategory { get; set; } = 0; + public int ScrollOffset { get; set; } = 0; + + public static readonly CheatsheetCategory[] Categories = + [ + new( + "Calculus, Sum & Prod", + [ + ("sum(n=start, end, f(n))", "Summation notation Σ", "sum(n=1, 5, sin(n*x)/n)"), + ("prod(n=start, end, f(n))", "Product notation Π", "prod(n=1, 4, 1 + x/n)"), + ("int(t=a, b, f(t))", "Definite integral ∫ from a to b", "int(t=0, x, sin(t^2))"), + ("int(t=1, x, 1/t)", "Logarithm integral definition", "int(t=1, x, 1/t)"), + ("diff(t=x, f(t))", "Numerical derivative d/dx [f(x)]", "diff(t=x, sin(t^3))"), + ("x! or fact(x)", "Factorial n! (e.g. 5! = 120)", "x^3 / 3!"), + ("x!! or dfact(x)", "Double factorial n!! (e.g. 5!! = 15)", "x!!"), + ("x$ or sfact(x)", "Superfactorial n$ = 1!*2!*...*n! (4$ = 288)", "x$"), + ("gamma(x)", "Lanczos Gamma function Γ(x)", "gamma(x + 1)") + ] + ), + new( + "Double-Sided Equations", + [ + ("y = f(x)", "Explicit Cartesian curve (evaluated along x)", "y = sin(x) + 0.5x"), + ("f(y) = x", "Inverse curve (evaluated along y)", "y^2 = x"), + ("sin(y) = x", "Inverse sine wave along y-axis", "sin(y) = x"), + ("f(y) = g(x)", "Implicit relation via Marching Squares", "y^2 = sin(x)"), + ("sin(y) = cos(x)", "Double-sided trigonometric grid mesh", "sin(y) = cos(x)"), + ("y^2 = x^3 - 3x", "Weierstrass elliptic curve", "y^2 = x^3 - 3x"), + ("x^2 + y^2 = 25", "Circle of radius 5 (implicit)", "x^2 + y^2 = 25"), + ("y^2 - x^2 = 1", "Unit hyperbola (implicit)", "y^2 - x^2 = 1") + ] + ), + new( + "Trig & Hyperbolic", + [ + ("sin(x), cos(x), tan(x)", "Standard trigonometric functions", "sin(2x) * cos(x)"), + ("cot(x), sec(x), csc(x)", "Reciprocal trigonometric functions", "cot(x)"), + ("asin(x), acos(x), atan(x)", "Inverse trigonometric functions", "atan(x)"), + ("atan2(y, x)", "Four-quadrant inverse tangent", "atan2(y, x)"), + ("sinh(x), cosh(x), tanh(x)", "Hyperbolic trigonometric functions", "cosh(x) - sinh(x)") + ] + ), + new( + "Exponentials & Powers", + [ + ("exp(x)", "Natural exponential e^x", "exp(-0.2x)"), + ("ln(x)", "Natural logarithm (base e)", "ln(abs(x) + 1)"), + ("log(x)", "Common logarithm (base 10)", "log(x)"), + ("log2(x)", "Binary logarithm (base 2)", "log2(x)"), + ("sqrt(x), cbrt(x)", "Square root and cube root", "sqrt(x) + cbrt(x)"), + ("x^y", "Power operator (e.g. 2^x, x^3)", "x^3 - 2x + 1") + ] + ), + new( + "Utilities & Constants", + [ + ("pi, e, tau, phi", "Math constants: π, e, 2π, (1+√5)/2", "sin(pi * x)"), + ("abs(x)", "Absolute value |x|", "abs(x)"), + ("floor(x), ceil(x), round(x)", "Rounding functions", "floor(x)"), + ("sgn(x) or sign(x)", "Signum function (-1, 0, 1)", "sgn(x)"), + ("min(a, b), max(a, b)", "Minimum and maximum", "max(sin(x), cos(x))"), + ("clamp(x, min, max)", "Restricts value between min and max", "clamp(x, -2, 2)"), + ("Implicit Multiplication", "Supported: 2x, 3sin(x), (x+1)(x-1)", "2x + 3sin(x)") + ] + ) + ]; + + public void HandleKey(KeyAction key, Action? onInsertExample = null) + { + if (!IsOpen) return; + + switch (key.Code) + { + case KeyCode.Escape or KeyCode.F5: + IsOpen = false; + break; + + case KeyCode.Left or KeyCode.Char when key.KeyChar == 'h': + if (SelectedCategory > 0) + { + SelectedCategory--; + ScrollOffset = 0; + } + break; + + case KeyCode.Right or KeyCode.Char when key.KeyChar == 'l': + if (SelectedCategory < Categories.Length - 1) + { + SelectedCategory++; + ScrollOffset = 0; + } + break; + + case KeyCode.Up or KeyCode.Char when key.KeyChar == 'k': + if (ScrollOffset > 0) ScrollOffset--; + break; + + case KeyCode.Down or KeyCode.Char when key.KeyChar == 'j': + var cat = Categories[SelectedCategory]; + if (ScrollOffset < cat.Entries.Length - 1) ScrollOffset++; + break; + + case KeyCode.Tab: + SelectedCategory = (SelectedCategory + 1) % Categories.Length; + ScrollOffset = 0; + break; + + case KeyCode.Enter: + var currCat = Categories[SelectedCategory]; + if (ScrollOffset >= 0 && ScrollOffset < currCat.Entries.Length) + { + IsOpen = false; + onInsertExample?.Invoke(currCat.Entries[ScrollOffset].Example); + } + break; + + case KeyCode.Char when key.KeyChar is >= '1' and <= '5': + int num = key.KeyChar - '1'; + if (num < Categories.Length) + { + SelectedCategory = num; + ScrollOffset = 0; + } + break; + } + } + + public bool HandleMouse(MouseEvent mouse, int screenWidth, int screenHeight, Action? onInsertExample = null) + { + if (!IsOpen || mouse.Type != MouseEventType.Down) return false; + + int modalW = System.Math.Min(82, screenWidth - 4); + int modalH = System.Math.Min(26, screenHeight - 2); + int col = (screenWidth - modalW) / 2; + int row = (screenHeight - modalH) / 2; + + if (mouse.Col < col || mouse.Col >= col + modalW || mouse.Row < row || mouse.Row >= row + modalH) + { + IsOpen = false; + return true; + } + + // Check if category tab was clicked (row + 1) + if (mouse.Row == row + 1) + { + int tabCol = col + 2; + for (int i = 0; i < Categories.Length; i++) + { + string tabName = $"[{i + 1}. {Categories[i].Title}]"; + if (mouse.Col >= tabCol && mouse.Col < tabCol + tabName.Length) + { + SelectedCategory = i; + ScrollOffset = 0; + return true; + } + tabCol += tabName.Length + 1; + } + } + + // Check if an entry was clicked to load + var cat = Categories[SelectedCategory]; + int listStartRow = row + 4; + for (int i = 0; i < cat.Entries.Length; i++) + { + int entryRow = listStartRow + i * 2; + if (mouse.Row == entryRow || mouse.Row == entryRow + 1) + { + ScrollOffset = i; + IsOpen = false; + onInsertExample?.Invoke(cat.Entries[i].Example); + return true; + } + } + + return false; + } + + public void Render(VirtualScreen screen, int screenWidth, int screenHeight) + { + if (!IsOpen) return; + + int modalW = System.Math.Min(82, screenWidth - 4); + int modalH = System.Math.Min(26, screenHeight - 2); + int col = (screenWidth - modalW) / 2; + int row = (screenHeight - modalH) / 2; + + screen.DrawBox(col, row, modalW, modalH, ColorRgb.Accent, ColorRgb.SidebarBg, "Math Engine Cheatsheet (Tab/1-5: Categories, Enter: Load, Esc: Close)"); + + // 1. Category Tabs Bar + int tabCol = col + 2; + for (int i = 0; i < Categories.Length; i++) + { + bool isTabActive = i == SelectedCategory; + string tabName = $"[{i + 1}. {Categories[i].Title}]"; + ColorRgb tabFg = isTabActive ? ColorRgb.Yellow : ColorRgb.Gray; + ColorRgb tabBg = isTabActive ? new ColorRgb(35, 45, 65) : ColorRgb.SidebarBg; + + screen.DrawText(tabCol, row + 1, tabName, tabFg, tabBg); + tabCol += tabName.Length + 1; + } + + // Separator line + for (int c = col + 1; c < col + modalW - 1; c++) + { + screen.SetCell(c, row + 2, '─', ColorRgb.GridLine, ColorRgb.SidebarBg); + } + + // 2. Entries in Selected Category + var cat = Categories[SelectedCategory]; + int listStartRow = row + 3; + int maxItems = (modalH - 5) / 2; + + for (int i = 0; i < cat.Entries.Length && i < maxItems; i++) + { + var entry = cat.Entries[i]; + int entryRow = listStartRow + i * 2; + bool isSelected = i == ScrollOffset; + + ColorRgb rowBg = isSelected ? new ColorRgb(35, 45, 65) : ColorRgb.SidebarBg; + + // Clear background + screen.DrawText(col + 1, entryRow, new string(' ', modalW - 2), ColorRgb.White, rowBg); + screen.DrawText(col + 1, entryRow + 1, new string(' ', modalW - 2), ColorRgb.White, rowBg); + + // Cursor and Syntax + char cursor = isSelected ? '▶' : ' '; + screen.SetCell(col + 2, entryRow, cursor, ColorRgb.Yellow, rowBg); + screen.DrawText(col + 4, entryRow, entry.Syntax, isSelected ? ColorRgb.Yellow : ColorRgb.Cyan, rowBg, 35); + + // Description + screen.DrawText(col + 40, entryRow, entry.Description, ColorRgb.White, rowBg, modalW - 42); + + // Example + string exampleTag = $"Example: {entry.Example}"; + screen.DrawText(col + 6, entryRow + 1, exampleTag, ColorRgb.Green, rowBg, modalW - 8); + } + + // Bottom guide + string bottomGuide = "Tip: Press Enter on any function to immediately plot its example!"; + screen.DrawText(col + 3, row + modalH - 2, bottomGuide, ColorRgb.DarkGray, ColorRgb.SidebarBg, modalW - 6); + } +} diff --git a/src/GraphTUI/UI/Views/HelpModal.cs b/src/GraphTUI/UI/Views/HelpModal.cs index 16c0a8f..fad84e7 100644 --- a/src/GraphTUI/UI/Views/HelpModal.cs +++ b/src/GraphTUI/UI/Views/HelpModal.cs @@ -56,19 +56,21 @@ public sealed class HelpModal Row("t (in Canvas)", "Toggle Trace Mode (crosshair with dy/dx readout)", ColorRgb.Cyan, ColorRgb.White); Row("c / F3", "Open Calculus Tools (Roots, Extrema, Integral, Tangent)", ColorRgb.Cyan, ColorRgb.White); Row("p / F4", "Open Mathematical Presets Gallery", ColorRgb.Cyan, ColorRgb.White); + Row("F5 / :cheat", "Open Function Usage Cheatsheet & Notation Guide", ColorRgb.Cyan, ColorRgb.White); Row(": (colon)", "Open Command Bar (:save, :load, :export, :quit)", ColorRgb.Cyan, ColorRgb.White); Row("--- FUNCTION MANAGEMENT ---", "", ColorRgb.Yellow, ColorRgb.SidebarBg); - Row("a / +", "Add new function (Cartesian, Parametric, Polar)", ColorRgb.Cyan, ColorRgb.White); + Row("a / +", "Add equation (y=f(x), f(y)=x, f(y)=g(x))", ColorRgb.Cyan, ColorRgb.White); Row("Space / Click check", "Toggle visibility of selected function", ColorRgb.Cyan, ColorRgb.White); Row("c / Click dot", "Cycle function color from vibrant palette", ColorRgb.Cyan, ColorRgb.White); Row("e / Enter", "Edit formula expression", ColorRgb.Cyan, ColorRgb.White); Row("d / Delete", "Delete selected function", ColorRgb.Cyan, ColorRgb.White); - Row("--- MATH ENGINE SYNTAX ---", "", ColorRgb.Yellow, ColorRgb.SidebarBg); - Row("Implicit Multiplication", "2x, 3sin(x), (x+1)(x-1), 2pi", ColorRgb.Green, ColorRgb.White); - Row("Supported Functions", "sin, cos, tan, cot, asin, acos, atan, sinh, cosh", ColorRgb.Green, ColorRgb.White); - Row("Advanced Functions", "exp, ln, log, log2, sqrt, cbrt, abs, floor, ceil", ColorRgb.Green, ColorRgb.White); - Row("Parameters & Constants", "Variables x, t, theta; Params a,b,c; pi, e, tau, phi", ColorRgb.Green, ColorRgb.White); + Row("--- MATH & CALCULUS SYNTAX ---", "", ColorRgb.Yellow, ColorRgb.SidebarBg); + Row("sum(n=1, 5, f(n))", "Summation notation: sum(n=start, end, expr)", ColorRgb.Green, ColorRgb.White); + Row("prod(n=1, 4, f(n))", "Product notation: prod(n=start, end, expr)", ColorRgb.Green, ColorRgb.White); + Row("int(t=a, b, f(t))", "Definite integral: int(t=0, x, sin(t^2))", ColorRgb.Green, ColorRgb.White); + Row("diff(t=x, f(t))", "Numerical derivative operator d/dx [f(x)]", ColorRgb.Green, ColorRgb.White); + Row("fact(n), gamma(x)", "Factorials and Gamma functions", ColorRgb.Green, ColorRgb.White); } } diff --git a/src/GraphTUI/UI/Views/PresetsGalleryModal.cs b/src/GraphTUI/UI/Views/PresetsGalleryModal.cs index 8bb44ae..c7ccf26 100644 --- a/src/GraphTUI/UI/Views/PresetsGalleryModal.cs +++ b/src/GraphTUI/UI/Views/PresetsGalleryModal.cs @@ -78,6 +78,48 @@ public sealed class PresetsGalleryModal ThetaMax: 2 * System.Math.PI, Color: ColorRgb.Purple ), + new( + "Horizontal Parabola (f(y)=x)", + "Direct inverse function: y^2 = x", + FunctionType.CartesianX, + "y^2 = x", + Color: ColorRgb.Orange + ), + new( + "Elliptic Curve (f(y)=g(x))", + "Double-sided Weierstrass elliptic curve: y^2 = x^3 - 3x", + FunctionType.Implicit, + "y^2 = x^3 - 3x", + Color: ColorRgb.Cyan + ), + new( + "Double-Sided Trig Mesh", + "Implicit wave interference pattern: sin(y) = cos(x)", + FunctionType.Implicit, + "sin(y) = cos(x)", + Color: ColorRgb.Yellow + ), + new( + "Fresnel Integral Function (int)", + "Non-elementary definite integral: int(t=0, x, sin(t^2))", + FunctionType.Cartesian, + "int(t=0, x, sin(t^2))", + Color: ColorRgb.Magenta + ), + new( + "Fourier Summation Series (sum)", + "Finite odd harmonic sum: sum(n=1, 6, sin((2n-1)x)/(2n-1))", + FunctionType.Cartesian, + "sum(n=1, 6, sin((2n-1)*x)/(2n-1))", + Color: ColorRgb.Green + ), + new( + "Euler Infinite Product proxy (prod)", + "Finite Weierstrass product for sinc: prod(n=1, 4, 1 - (x/(n*pi))^2)", + FunctionType.Cartesian, + "prod(n=1, 4, 1 - (x/(n*pi))^2)", + Color: ColorRgb.Cyan + ), new( "Interactive Wave Interference", "Adjustable dual-frequency wave: sin(a*x) + cos(b*x)", diff --git a/tests/GraphTUI.Tests/DoubleSidedEquationTests.cs b/tests/GraphTUI.Tests/DoubleSidedEquationTests.cs new file mode 100644 index 0000000..7f20a83 --- /dev/null +++ b/tests/GraphTUI.Tests/DoubleSidedEquationTests.cs @@ -0,0 +1,128 @@ +using GraphTUI.Core.Models; +using GraphTUI.Rendering; + +namespace GraphTUI.Tests; + +public static class DoubleSidedEquationTests +{ + public static void Register(TestRunner runner) + { + runner.Add("DoubleSided: y = f(x) definitions", () => + { + var fn1 = new GraphFunction(1, "y = sin(x)", ColorRgb.Cyan); + Assert.Equal(FunctionType.Cartesian, fn1.Type); + Assert.True(fn1.CompilationError == null, $"Unexpected error: {fn1.CompilationError}"); + Assert.Equal(0.0, fn1.Evaluator!.Evaluate(0)); + Assert.Within(1.0, fn1.Evaluator.Evaluate(System.Math.PI / 2), 1e-6); + + // Inverted order: sin(x) = y + var fn2 = new GraphFunction(2, "sin(x) = y", ColorRgb.Yellow); + Assert.Equal(FunctionType.Cartesian, fn2.Type); + Assert.True(fn2.CompilationError == null); + Assert.Within(1.0, fn2.Evaluator!.Evaluate(System.Math.PI / 2), 1e-6); + + // Plain expression sin(x) defaults to y = sin(x) + var fn3 = new GraphFunction(3, "sin(x)", ColorRgb.Green); + Assert.Equal(FunctionType.Cartesian, fn3.Type); + Assert.True(fn3.CompilationError == null); + }); + + runner.Add("DoubleSided: f(y) = x and x = f(y) definitions", () => + { + // x = y^2 + var fn1 = new GraphFunction(1, "x = y^2", ColorRgb.Cyan); + Assert.Equal(FunctionType.CartesianX, fn1.Type); + Assert.True(fn1.CompilationError == null, $"Unexpected error: {fn1.CompilationError}"); + Assert.Equal(9.0, fn1.Evaluator!.EvaluateY(3)); + Assert.Equal(9.0, fn1.Evaluator.EvaluateY(-3)); + + // f(y) = x: y^2 = x + var fn2 = new GraphFunction(2, "y^2 = x", ColorRgb.Yellow); + Assert.Equal(FunctionType.CartesianX, fn2.Type); + Assert.True(fn2.CompilationError == null); + Assert.Equal(16.0, fn2.Evaluator!.EvaluateY(4)); + Assert.Equal(16.0, fn2.Evaluator.EvaluateY(-4)); + + // sin(y) = x + var fn3 = new GraphFunction(3, "sin(y) = x", ColorRgb.Magenta); + Assert.Equal(FunctionType.CartesianX, fn3.Type); + Assert.True(fn3.CompilationError == null); + Assert.Within(1.0, fn3.Evaluator!.EvaluateY(System.Math.PI / 2), 1e-6); + + // y^3 + 2y = x + var fn4 = new GraphFunction(4, "y^3 + 2y = x", ColorRgb.Orange); + Assert.Equal(FunctionType.CartesianX, fn4.Type); + Assert.True(fn4.CompilationError == null); + Assert.Equal(12.0, fn4.Evaluator!.EvaluateY(2)); // 2^3 + 2*2 = 8 + 4 = 12 + + // Plain expression with y and no x: y^2 defaults to x = y^2 + var fn5 = new GraphFunction(5, "y^2", ColorRgb.White); + Assert.Equal(FunctionType.CartesianX, fn5.Type); + Assert.True(fn5.CompilationError == null); + Assert.Equal(4.0, fn5.Evaluator!.EvaluateY(2)); + }); + + runner.Add("DoubleSided: f(y) = g(x) and implicit definitions", () => + { + // y^2 = sin(x) + var fn1 = new GraphFunction(1, "y^2 = sin(x)", ColorRgb.Cyan); + Assert.Equal(FunctionType.Implicit, fn1.Type); + Assert.True(fn1.CompilationError == null, $"Unexpected error: {fn1.CompilationError}"); + Assert.True(fn1.EvaluatorLhs != null && fn1.EvaluatorRhs != null); + Assert.Equal(4.0, fn1.EvaluatorLhs!.EvaluateY(2)); + Assert.Within(1.0, fn1.EvaluatorRhs!.Evaluate(System.Math.PI / 2), 1e-6); + + // sin(y) = cos(x) + var fn2 = new GraphFunction(2, "sin(y) = cos(x)", ColorRgb.Yellow); + Assert.Equal(FunctionType.Implicit, fn2.Type); + Assert.True(fn2.CompilationError == null); + + // Elliptic curve: y^2 = x^3 - 3x + var fn3 = new GraphFunction(3, "y^2 = x^3 - 3x", ColorRgb.Green); + Assert.Equal(FunctionType.Implicit, fn3.Type); + Assert.True(fn3.CompilationError == null); + + // Circle: x^2 + y^2 = 25 + var fn4 = new GraphFunction(4, "x^2 + y^2 = 25", ColorRgb.Magenta); + Assert.Equal(FunctionType.Implicit, fn4.Type); + Assert.True(fn4.CompilationError == null); + }); + + runner.Add("DoubleSided: Rendering f(y) = x and f(y) = g(x) on Braille Canvas", () => + { + var canvas = new BrailleCanvas(40, 20); + var viewport = new Viewport { XMin = -10, XMax = 10, YMin = -10, YMax = 10 }; + + // 1. Test f(y) = x: y^2 = x + var fnX = new GraphFunction(1, "y^2 = x", ColorRgb.Cyan); + PlotRenderer.Render(canvas, viewport, [fnX], _ => 0); + + // Count non-empty Braille cells + int cellsWithDots = 0; + for (int r = 0; r < canvas.CellHeight; r++) + { + for (int c = 0; c < canvas.CellWidth; c++) + { + var (ch, _, _) = canvas.GetCell(c, r); + if (ch != ' ') cellsWithDots++; + } + } + Assert.True(cellsWithDots > 5, $"Expected plotted dots for y^2=x, got {cellsWithDots}"); + + // 2. Test f(y) = g(x): y^2 = sin(x) + var fnImplicit = new GraphFunction(2, "y^2 = sin(x)", ColorRgb.Yellow); + PlotRenderer.Render(canvas, viewport, [fnImplicit], _ => 0); + + int implicitDots = 0; + for (int r = 0; r < canvas.CellHeight; r++) + { + for (int c = 0; c < canvas.CellWidth; c++) + { + var (ch, _, _) = canvas.GetCell(c, r); + if (ch != ' ') implicitDots++; + } + } + Assert.True(implicitDots > 5, $"Expected plotted dots for y^2=sin(x), got {implicitDots}"); + }); + } +} diff --git a/tests/GraphTUI.Tests/FactorialVariantsTests.cs b/tests/GraphTUI.Tests/FactorialVariantsTests.cs new file mode 100644 index 0000000..0191b5d --- /dev/null +++ b/tests/GraphTUI.Tests/FactorialVariantsTests.cs @@ -0,0 +1,215 @@ +using GraphTUI.Core.Math; +using GraphTUI.Core.Models; +using GraphTUI.Rendering; +using System.Diagnostics; + +namespace GraphTUI.Tests; + +public static class FactorialVariantsTests +{ + public static void Register(TestRunner runner) + { + runner.Add("Factorials: x! postfix and fact(x)", () => + { + // 0! = 1 + var eval0 = Evaluator.Compile("0!"); + Assert.Equal(1.0, eval0.Evaluate(0)); + + // 5! = 120 + var eval5 = Evaluator.Compile("5!"); + Assert.Equal(120.0, eval5.Evaluate(0)); + + // Variable x! + var evalX = Evaluator.Compile("x!"); + Assert.Equal(6.0, evalX.Evaluate(3.0)); + Assert.Equal(24.0, evalX.Evaluate(4.0)); + Assert.Equal(120.0, evalX.Evaluate(5.0)); + + // Parenthesized (x + 1)! + var evalParen = Evaluator.Compile("(x + 1)!"); + Assert.Equal(24.0, evalParen.Evaluate(3.0)); // (3+1)! = 4! = 24 + + // fact(x) equivalence + var evalFunc = Evaluator.Compile("fact(4)"); + Assert.Equal(24.0, evalFunc.Evaluate(0)); + + // Implicit multiplication with factorial: 2x! at x=3 -> 2 * 6 = 12 + var evalImplicit = Evaluator.Compile("2x!"); + Assert.Equal(12.0, evalImplicit.Evaluate(3.0)); + + // Unary minus: -3! -> -(3!) = -6 + var evalUnary = Evaluator.Compile("-3!"); + Assert.Equal(-6.0, evalUnary.Evaluate(0)); + }); + + runner.Add("Double Factorials: x!! postfix and dfact(x)", () => + { + // 0!! = 1, (-1)!! = 1 + var eval0 = Evaluator.Compile("0!!"); + Assert.Equal(1.0, eval0.Evaluate(0)); + + // 5!! = 5 * 3 * 1 = 15 + var eval5 = Evaluator.Compile("5!!"); + Assert.Equal(15.0, eval5.Evaluate(0)); + + // 6!! = 6 * 4 * 2 = 48 + var eval6 = Evaluator.Compile("6!!"); + Assert.Equal(48.0, eval6.Evaluate(0)); + + // 7!! = 7 * 5 * 3 * 1 = 105 + var eval7 = Evaluator.Compile("7!!"); + Assert.Equal(105.0, eval7.Evaluate(0)); + + // Variable x!! + var evalX = Evaluator.Compile("x!!"); + Assert.Equal(15.0, evalX.Evaluate(5.0)); + Assert.Equal(48.0, evalX.Evaluate(6.0)); + + // dfact(x) function syntax + var evalFunc = Evaluator.Compile("dfact(5)"); + Assert.Equal(15.0, evalFunc.Evaluate(0)); + + // (x + 1)!! + var evalParen = Evaluator.Compile("(x + 1)!!"); + Assert.Equal(15.0, evalParen.Evaluate(4.0)); // (4+1)!! = 5!! = 15 + }); + + runner.Add("Super Factorials: x$ postfix and sfact(x)", () => + { + // 1$ = 1! = 1 + var eval1 = Evaluator.Compile("1$"); + Assert.Equal(1.0, eval1.Evaluate(0)); + + // 2$ = 1! * 2! = 2 + var eval2 = Evaluator.Compile("2$"); + Assert.Equal(2.0, eval2.Evaluate(0)); + + // 3$ = 1! * 2! * 3! = 1 * 2 * 6 = 12 + var eval3 = Evaluator.Compile("3$"); + Assert.Equal(12.0, eval3.Evaluate(0)); + + // 4$ = 1! * 2! * 3! * 4! = 12 * 24 = 288 + var eval4 = Evaluator.Compile("4$"); + Assert.Equal(288.0, eval4.Evaluate(0)); + + // Variable x$ + var evalX = Evaluator.Compile("x$"); + Assert.Equal(12.0, evalX.Evaluate(3.0)); + Assert.Equal(288.0, evalX.Evaluate(4.0)); + + // sfact(x) function syntax + var evalFunc = Evaluator.Compile("sfact(4)"); + Assert.Equal(288.0, evalFunc.Evaluate(0)); + }); + + runner.Add("Compound expressions with !, !!, and $", () => + { + // 3! + 4!! = 6 + 8 = 14 + var eval1 = Evaluator.Compile("3! + 4!!"); + Assert.Equal(14.0, eval1.Evaluate(0)); + + // (3!)! = 6! = 720 + var eval2 = Evaluator.Compile("(3!)!"); + Assert.Equal(720.0, eval2.Evaluate(0)); + + // Taylor series using postfix x! in sum: sum(n=0, 4, x^n / n!) + // For x=1: 1 + 1 + 1/2 + 1/6 + 1/24 = 65/24 ~ 2.708333 + var evalTaylor = Evaluator.Compile("sum(n=0, 4, x^n / n!)"); + Assert.Within(65.0 / 24.0, evalTaylor.Evaluate(1.0), 1e-4); + }); + + runner.Add("Factorials: Edge cases, lookup tables, and limits", () => + { + // 20! = 2,432,902,008,176,640,000 + var eval20 = Evaluator.Compile("20!"); + Assert.Equal(2432902008176640000.0, eval20.Evaluate(0)); + + // 170! is the maximum finite IEEE double factorial (~7.2574e306) + var eval170 = Evaluator.Compile("170!"); + double f170 = eval170.Evaluate(0); + Assert.True(!double.IsInfinity(f170) && f170 > 1e306, "170! should be finite and > 1e306"); + + // 171! overflows double to infinity + var eval171 = Evaluator.Compile("171!"); + Assert.True(double.IsPositiveInfinity(eval171.Evaluate(0)), "171! should be PositiveInfinity"); + + // 300!! is finite + var eval300 = Evaluator.Compile("300!!"); + double df300 = eval300.Evaluate(0); + Assert.True(!double.IsInfinity(df300) && df300 > 1e300, "300!! should be finite"); + + // 302!! overflows double + var eval302 = Evaluator.Compile("302!!"); + Assert.True(double.IsPositiveInfinity(eval302.Evaluate(0)), "302!! should be PositiveInfinity"); + + // Negative integer poles return NaN + var evalNegInt = Evaluator.Compile("(-1)!"); + Assert.True(double.IsNaN(evalNegInt.Evaluate(0)), "(-1)! should be NaN"); + + var evalNegInt2 = Evaluator.Compile("(-2)!"); + Assert.True(double.IsNaN(evalNegInt2.Evaluate(0)), "(-2)! should be NaN"); + + // Non-integer factorial: (-0.5)! = Gamma(0.5) = sqrt(pi) ~ 1.77245385 + var evalHalf = Evaluator.Compile("(-0.5)!"); + Assert.Within(System.Math.Sqrt(System.Math.PI), evalHalf.Evaluate(0), 1e-5); + }); + + runner.Add("Factorials: Performance stress test (zero lag on x!, x!!, x$)", () => + { + var canvas = new BrailleCanvas(80, 25); // 160 x 100 subpixels + var viewport = new Viewport + { + XMin = -10.0, + XMax = 10.0, + YMin = -5.0, + YMax = 5.0 + }; + + // 1. Rendering y = x! over viewport: must complete in < 50ms (previously took seconds or froze) + var fnFact = new GraphFunction(1, "y = x!", ColorRgb.Cyan); + var sw = Stopwatch.StartNew(); + for (int frame = 0; frame < 5; frame++) + { + PlotRenderer.Render(canvas, viewport, [fnFact], _ => 0); + } + sw.Stop(); + long elapsedFact = sw.ElapsedMilliseconds; + Assert.True(elapsedFact < 200, $"5 frames of y = x! took {elapsedFact}ms (expected < 200ms)"); + + // 2. Rendering y = x!! over viewport + var fnDfact = new GraphFunction(2, "y = x!!", ColorRgb.Yellow); + sw.Restart(); + for (int frame = 0; frame < 5; frame++) + { + PlotRenderer.Render(canvas, viewport, [fnDfact], _ => 0); + } + sw.Stop(); + long elapsedDfact = sw.ElapsedMilliseconds; + Assert.True(elapsedDfact < 200, $"5 frames of y = x!! took {elapsedDfact}ms (expected < 200ms)"); + + // 3. Rendering y = x$ over viewport + var fnSfact = new GraphFunction(3, "y = x$", ColorRgb.Green); + sw.Restart(); + for (int frame = 0; frame < 5; frame++) + { + PlotRenderer.Render(canvas, viewport, [fnSfact], _ => 0); + } + sw.Stop(); + long elapsedSfact = sw.ElapsedMilliseconds; + Assert.True(elapsedSfact < 200, $"5 frames of y = x$ took {elapsedSfact}ms (expected < 200ms)"); + + // 4. Batch mathematical evaluation of 100,000 points + var eval = Evaluator.Compile("x!"); + sw.Restart(); + double sum = 0.0; + for (int i = 0; i < 100_000; i++) + { + sum += eval.Evaluate(i % 172); + } + sw.Stop(); + long elapsed100k = sw.ElapsedMilliseconds; + Assert.True(elapsed100k < 100, $"100,000 factorial evaluations took {elapsed100k}ms (expected < 100ms)"); + Assert.True(!double.IsNaN(sum), "Sum of evaluations should not be NaN"); + }); + } +} diff --git a/tests/GraphTUI.Tests/Program.cs b/tests/GraphTUI.Tests/Program.cs index 6270306..827f037 100644 --- a/tests/GraphTUI.Tests/Program.cs +++ b/tests/GraphTUI.Tests/Program.cs @@ -11,6 +11,9 @@ public static class Program CalculusTests.Register(runner); BrailleCanvasTests.Register(runner); ExportSessionTests.Register(runner); + DoubleSidedEquationTests.Register(runner); + SummationProductIntegralTests.Register(runner); + FactorialVariantsTests.Register(runner); return runner.RunAll(); } diff --git a/tests/GraphTUI.Tests/SummationProductIntegralTests.cs b/tests/GraphTUI.Tests/SummationProductIntegralTests.cs new file mode 100644 index 0000000..03871da --- /dev/null +++ b/tests/GraphTUI.Tests/SummationProductIntegralTests.cs @@ -0,0 +1,98 @@ +using GraphTUI.Core.Math; + +namespace GraphTUI.Tests; + +public static class SummationProductIntegralTests +{ + public static void Register(TestRunner runner) + { + runner.Add("Summation: sum(n=start, end, f(n)) and sum(n, start, end, f(n))", () => + { + // sum(n=1, 5, n) = 1 + 2 + 3 + 4 + 5 = 15 + var eval1 = Evaluator.Compile("sum(n=1, 5, n)"); + Assert.Equal(15.0, eval1.Evaluate(0)); + + // sum(n=1, 4, n^2) = 1 + 4 + 9 + 16 = 30 + var eval2 = Evaluator.Compile("sum(n=1, 4, n^2)"); + Assert.Equal(30.0, eval2.Evaluate(0)); + + // sum with variable x: sum(n=1, 3, n*x) = 1x + 2x + 3x = 6x -> for x=2, result is 12 + var eval3 = Evaluator.Compile("sum(n=1, 3, n*x)"); + Assert.Equal(12.0, eval3.Evaluate(2.0)); + + // sum(k=0, 4, 2^k) = 1 + 2 + 4 + 8 + 16 = 31 + var eval4 = Evaluator.Compile("sum(k=0, 4, 2^k)"); + Assert.Equal(31.0, eval4.Evaluate(0)); + + // sum with comma syntax: sum(n, 1, 5, n) + var eval5 = Evaluator.Compile("sum(n, 1, 5, n)"); + Assert.Equal(15.0, eval5.Evaluate(0)); + }); + + runner.Add("Product notation: prod(n=start, end, f(n)) and prod(n, start, end, f(n))", () => + { + // prod(n=1, 5, n) = 1 * 2 * 3 * 4 * 5 = 120 + var eval1 = Evaluator.Compile("prod(n=1, 5, n)"); + Assert.Equal(120.0, eval1.Evaluate(0)); + + // prod with variable x: prod(n=1, 3, x + n) -> for x=1: 2 * 3 * 4 = 24 + var eval2 = Evaluator.Compile("prod(n=1, 3, x + n)"); + Assert.Equal(24.0, eval2.Evaluate(1.0)); + + // prod with comma syntax: prod(i, 1, 4, 2) = 2^4 = 16 + var eval3 = Evaluator.Compile("prod(i, 1, 4, 2)"); + Assert.Equal(16.0, eval3.Evaluate(0)); + }); + + runner.Add("Calculus Integrals: int(t=a, b, f(t)) and integral(t, a, b, f(t))", () => + { + // int(t=0, x, 2t) = [t^2]_0^x = x^2 -> for x=3, result is 9 + var eval1 = Evaluator.Compile("int(t=0, x, 2*t)"); + Assert.Within(9.0, eval1.Evaluate(3.0), 1e-4); + + // int(t=0, pi, sin(t)) = 2.0 + var eval2 = Evaluator.Compile("int(t=0, pi, sin(t))"); + Assert.Within(2.0, eval2.Evaluate(0), 1e-4); + + // int(t=1, e, 1/t) = ln(e) - ln(1) = 1.0 + var eval3 = Evaluator.Compile("integral(t=1, e, 1/t)"); + Assert.Within(1.0, eval3.Evaluate(0), 1e-4); + + // Gaussian integral error function proxy: int(t=0, 1, exp(-t^2)) + var eval4 = Evaluator.Compile("int(t=0, 1, exp(-t^2))"); + Assert.Within(0.746824, eval4.Evaluate(0), 1e-3); + }); + + runner.Add("Calculus Derivatives: diff(t=x, f(t)) and diff(f(x), x)", () => + { + // d/dx [x^3] at x=2 is 3*(2^2) = 12 + var eval1 = Evaluator.Compile("diff(t=x, t^3)"); + Assert.Within(12.0, eval1.Evaluate(2.0), 1e-4); + + // d/dx [sin(x)] at x=0 is cos(0) = 1 + var eval2 = Evaluator.Compile("diff(sin(x), x)"); + Assert.Within(1.0, eval2.Evaluate(0.0), 1e-4); + + // d/dx [exp(x)] at x=1 is e + var eval3 = Evaluator.Compile("diff(exp(x), x)"); + Assert.Within(System.Math.E, eval3.Evaluate(1.0), 1e-4); + }); + + runner.Add("Factorials and Gamma functions: fact(n) and gamma(x)", () => + { + var evalFact = Evaluator.Compile("fact(x)"); + Assert.Equal(1.0, evalFact.Evaluate(0)); + Assert.Equal(1.0, evalFact.Evaluate(1)); + Assert.Equal(2.0, evalFact.Evaluate(2)); + Assert.Equal(6.0, evalFact.Evaluate(3)); + Assert.Equal(24.0, evalFact.Evaluate(4)); + Assert.Equal(120.0, evalFact.Evaluate(5)); + + var evalGamma = Evaluator.Compile("gamma(x)"); + // Gamma(5) = 4! = 24 + Assert.Within(24.0, evalGamma.Evaluate(5.0), 1e-4); + // Gamma(1.5) = sqrt(pi) / 2 ~ 0.886227 + Assert.Within(0.886227, evalGamma.Evaluate(1.5), 1e-4); + }); + } +}