diff --git a/AGENTS.md b/AGENTS.md index a1b4436222..480a3c88c2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -12,6 +12,8 @@ sets the working practice for both. When there is nothing to do here, it goes ba `build` runs `src/NaiveStaticGenerator`, which wraps every page in `src/content` in `src/content/_templates/top.html` and `bottom.html` and writes `.output/final`. `run` builds and opens the home page. +- `build` then publishes `live/`, AngouriMath Live, the library in the browser as WebAssembly, and + copies it to `.output/final/live`. The nav's *Try online* leads there. See `live/README.md`. - `.output/final` also gets the stylesheets, `img/`, `CNAME`, `robots.txt`, and a `sitemap.xml` and an `llms.txt` that the generator writes from the pages it produced. - A pull request builds the site on Windows, Linux and macOS (`build-test.yml`). @@ -24,7 +26,8 @@ sets the working practice for both. When there is nothing to do here, it goes ba ## What a release of the library owes the site The library's release checklist names it. The *What's new* page gets a block for the release, with -the link to `BREAKING-CHANGES.md` pinned to the release's tag, and the quickstart names the release. +the link to `BREAKING-CHANGES.md` pinned to the release's tag, and the quickstart names the release, and +`live/AmLive.csproj`, the web app at `/live`, references the release's package. The library's `docsamples` harness, run in its CI with this repository checked out, checks that every code sample here compiles, runs and prints what its page says. Its report is the place to look before editing a sample. diff --git a/amsite.fsx b/amsite.fsx index 475d21f269..032a32b385 100644 --- a/amsite.fsx +++ b/amsite.fsx @@ -97,8 +97,31 @@ let uninit () = else dirDelete("." / generatorP / contentP / "_wiki") +// AngouriMath Live, the app in live/: the library in the browser as WebAssembly. It is published +// and copied to /live, after the generator, which writes the rest of .output/final. The runtime's +// precompressed .br and .gz copies are left out, since GitHub Pages compresses what it serves itself; +// what is left is the files dotnet.js loads. Its _framework folder is copied as framework, the name +// the page's worker imports dotnet.js by: a host that drops names starting with '_' cannot lose it, +// and dotnet.js finds the rest relative to its own URL. +let buildLive () = + let published = "." / ".output" / "live" + dotnet "live" $"publish -c Release -o {Path.GetFullPath published}" + let source = published / "wwwroot" + let target = "." / outputP / "live" + if dirExists target then dirDelete target + for file in Directory.GetFiles(source, "*", SearchOption.AllDirectories) do + if not (file.EndsWith ".br" || file.EndsWith ".gz") then + let relative = Path.GetRelativePath(source, file) + let relative = + if relative.StartsWith("_framework" + string Path.DirectorySeparatorChar) then relative.Substring 1 + else relative + let destination = target / relative + Directory.CreateDirectory(Path.GetDirectoryName destination) |> ignore + File.Copy(file, destination, true) + let build () = dotnet (generatorP / "NaiveStaticGenerator") "run" + buildLive () let run () = if RuntimeInformation.IsOSPlatform(OSPlatform.Windows) then diff --git a/live/AmLive.csproj b/live/AmLive.csproj new file mode 100644 index 0000000000..0d72d1d6ae --- /dev/null +++ b/live/AmLive.csproj @@ -0,0 +1,19 @@ + + + + net10.0 + Exe + enable + enable + true + true + + + + + + + + + diff --git a/live/Demos/Calculus.cs b/live/Demos/Calculus.cs new file mode 100644 index 0000000000..c987d2f7bf --- /dev/null +++ b/live/Demos/Calculus.cs @@ -0,0 +1,240 @@ +using System.Diagnostics; +using System.Text.Json.Nodes; +using AngouriMath; +using AngouriMath.Core; +using static AngouriMath.Entity; + +namespace AmLive; + +/// +/// The calculus demo: f(x), its first two derivatives and an antiderivative, all exact; the roots, +/// extrema and inflection points as solution sets; and Taylor polynomials closing in on f. +/// +public static class Calculus +{ + private const int MaxOrder = 8; + private static readonly Variable X = "x"; + + private static FastExpression? f, d1, d2, antiderivative; + private static FastExpression?[] taylor = new FastExpression?[MaxOrder + 1]; + private static Entity? exactAntiderivative; + + public static string Analyze(string text) + { + var clock = Stopwatch.StartNew(); + var e = Common.Parse(text, out var error); + if (e is null) + return Common.Fail(error); + var stray = e.Vars.Where(v => v != X).Select(v => v.Name).ToList(); + if (stray.Count > 0) + return Common.Fail($"Use x as the only variable. This formula also has {string.Join(", ", stray)}."); + + var first = Common.Try(() => Common.Unconditional(e.Differentiate(X)).Simplify()); + var second = first is null ? null : Common.Try(() => Common.Unconditional(first.Differentiate(X)).Simplify()); + var integral = Common.Try(() => e.Integrate(X).Simplify()); + // An integral AngouriMath could not find comes back as an integral node. + var found = integral is not null && !integral.Nodes.Any(n => n is Integralf); + exactAntiderivative = found ? integral!.Substitute("C", 0) : null; + + f = Common.TryCompile(e, X); + d1 = Common.TryCompile(first, X); + d2 = Common.TryCompile(second, X); + antiderivative = Common.TryCompile(exactAntiderivative, X); + + JsonObject Solved(Entity? of, string what) + { + var set = of is null ? null : Common.Try(() => (Entity)of.SolveEquation(X)); + return new JsonObject + { + ["what"] = what, + ["latex"] = set is null ? "" : Common.Latex(set), + ["text"] = set?.ToString() ?? "", + ["points"] = Common.Numbers(Common.RealPoints(set, -1e6, 1e6)), + // Decimals in the answer are what a numerical search found where no closed form was: + // the roots of tan x = x that sin(x)/x's extrema need, a few of infinitely many. + ["numerical"] = set is Entity.Set.FiniteSet found + && found.Any(root => root.Nodes.Any(node => node is Entity.Number.Real and not Entity.Number.Rational)), + }; + } + + return new JsonObject + { + ["ok"] = true, + ["f"] = Common.Latex(e), + ["d1"] = Common.Latex(first), + ["d2"] = Common.Latex(second), + ["integral"] = found ? Common.Latex(integral) : "", + ["roots"] = Solved(e, "roots"), + ["extrema"] = Solved(first, "extrema"), + ["inflections"] = Solved(second, "inflections"), + ["ms"] = clock.ElapsedMilliseconds, + }.ToJsonString(); + } + + /// Taylor polynomials of orders 0 to 8 around a, as LaTeX; also compiled for plotting. + public static string Taylor(string text, double a) + { + var e = Common.Parse(text, out var error); + if (e is null) + return Common.Fail(error); + // Expanding where f has no value (sin(x)/x at 0) sends AngouriMath through limits of + // ever larger quotients; it does not come back in useful time. + if (Common.Real(e.Substitute(X, a)) is null) + { + Array.Clear(taylor); + return Common.Fail($"f has no real value at x = {a:0.###}, so it has no Taylor polynomial there."); + } + // Built from the exact derivatives at a, each simplified before the next is taken: the + // library's Taylor simplifies the whole polynomial at the end, which for sin(x)/x at 1 + // took two minutes. + var latex = new JsonArray(); + Entity derivative = e, polynomial = 0, shift = a == 0 ? X : X - a, factorial = 1; + for (var order = 0; order <= MaxOrder; order++) + { + if (order > 0) + { + factorial *= order; + var next = Common.Try(() => Common.Unconditional(derivative.Differentiate(X)).Simplify()); + if (next is null) + { + for (; order <= MaxOrder; order++) + { + taylor[order] = null; + latex.Add(JsonValue.Create("")); + } + break; + } + derivative = next; + } + var coefficient = Common.Try(() => (derivative.Substitute(X, a) / factorial).Simplify()) ?? 0; + if (order == 0) + polynomial = coefficient; + else if (coefficient != 0) + { + var power = order == 1 ? shift : MathS.Pow(shift, order); + var term = coefficient == 1 ? power : coefficient * power; + polynomial = polynomial == 0 ? term : polynomial + term; + } + taylor[order] = Common.TryCompile(polynomial, X); + latex.Add(JsonValue.Create(taylor[order] is null ? "" : Common.Latex(polynomial))); + } + return new JsonObject { ["ok"] = true, ["latex"] = latex }.ToJsonString(); + } + + /// f, f', f'', the antiderivative and the Taylor polynomial of the given order over [from, to]. + public static double[] Sample(double from, double to, int n, int order) + { + var curves = new[] { f, d1, d2, antiderivative, order >= 0 && order <= MaxOrder ? taylor[order] : null }; + return curves.SelectMany(c => Common.Sample(c, from, to, n)).ToArray(); + } + + /// The area under f over [a, b]: exactly from the antiderivative, and by the midpoint rule as a check. + public static string Area(double a, double b) + { + string? exact = null, exactLatex = null; + double? exactValue = null; + if (exactAntiderivative is not null) + { + var area = Common.Try(() => (exactAntiderivative.Substitute(X, b) - exactAntiderivative.Substitute(X, a)).Simplify()); + if (area is not null) + { + exact = area.ToString(); + exactLatex = Common.Latex(area); + exactValue = Common.Real(area); + } + } + // Midpoints never touch the ends, where f may have no value (sin(x)/x at 0). + const int n = 4000; + var h = (b - a) / n; + var ys = Common.Sample(f, a + h / 2, b - h / 2, n); + var midpoint = ys.Sum() * h; + return new JsonObject + { + ["exact"] = exact, ["exactLatex"] = exactLatex, ["exactValue"] = exactValue, + ["numeric"] = double.IsFinite(midpoint) ? midpoint : null, + }.ToJsonString(); + } + + /// + /// The limits of f at both infinities, and on either side of each point near the origin where + /// a denominator or the argument of a logarithm is zero, which is where f may have a hole, a + /// jump or a pole. + /// + public static string Limits(string text) + { + var e = Common.Parse(text, out var error); + if (e is null) + return Common.Fail(error); + var points = new List<(Entity At, double Value)>(); + foreach (var node in e.Nodes) + { + var zero = node switch { Divf d => d.Divisor, Logf l => l.Antilogarithm, _ => null }; + if (zero is null || !zero.Vars.Contains(X)) + continue; + // A family such as the zeros of sin(x) is a union over an index, not a finite set; it is left out. + if (Common.Try(() => (Entity)zero.SolveEquation(X)) is not Entity.Set.FiniteSet zeros) + continue; + foreach (var z in zeros) + if (!z.Vars.Any() && Common.Real(z) is { } v && Math.Abs(v) <= 50 && !points.Any(p => Math.Abs(p.Value - v) < 1e-9)) + points.Add((Common.Try(() => z.Simplify()) ?? z, v)); + } + var near = new JsonArray(); + foreach (var (at, value) in points.OrderBy(p => Math.Abs(p.Value)).Take(4)) + near.Add(new JsonObject + { + ["at"] = Common.Latex(at), + ["x"] = value, + ["defined"] = Common.Real(e.Substitute(X, at)) is not null, + ["left"] = Limit(e, at, ApproachFrom.Left), + ["right"] = Limit(e, at, ApproachFrom.Right), + }); + return new JsonObject + { + ["ok"] = true, + ["minus"] = Limit(e, Number.Real.NegativeInfinity, ApproachFrom.BothSides), + ["plus"] = Limit(e, Number.Real.PositiveInfinity, ApproachFrom.BothSides), + ["points"] = near, + }.ToJsonString(); + } + + /// The limit of f at a point the reader chooses, from each side; at an infinity, the one there is. + public static string LimitAt(string text, string atText) + { + var e = Common.Parse(text, out var error); + var at = e is null ? null : Common.Parse(atText, out error); + if (e is null || at is null) + return Common.Fail(error); + if (at.Vars.Any() || Common.RealOrInfinite(at) is not { } value) + return Common.Fail("x has to approach a real number, +oo or -oo."); + var o = new JsonObject { ["ok"] = true, ["at"] = Common.Latex(at), ["x"] = double.IsFinite(value) ? value : null }; + if (double.IsFinite(value)) + { + o["left"] = Limit(e, at, ApproachFrom.Left); + o["right"] = Limit(e, at, ApproachFrom.Right); + o["value"] = Common.Real(e.Substitute(X, at)) is { } v ? v : null; + } + else + o["limit"] = Limit(e, at, ApproachFrom.BothSides); + return o.ToJsonString(); + } + + /// + /// One limit as LaTeX, with its kind: a real value, an infinity, none (AngouriMath answers NaN + /// where there is no limit, as for sin(x) at infinity) or unknown (it left the limit unevaluated). + /// + private static JsonObject Limit(Entity f, Entity at, ApproachFrom side) + { + var limit = Common.Try(() => Common.Unconditional(f.Limit(X, at, side))); + if (limit is null || limit.Nodes.Any(n => n is Limitf)) + return new JsonObject { ["kind"] = "unknown", ["latex"] = "" }; + if (limit.IsNaN) + return new JsonObject { ["kind"] = "none", ["latex"] = "" }; + var value = Common.RealOrInfinite(limit); + return new JsonObject + { + ["kind"] = value switch { double.PositiveInfinity => "+oo", double.NegativeInfinity => "-oo", null => "other", _ => "value" }, + ["latex"] = Common.Latex(limit), + ["value"] = value is { } v && double.IsFinite(v) ? v : null, + }; + } +} diff --git a/live/Demos/Common.cs b/live/Demos/Common.cs new file mode 100644 index 0000000000..6f3c2f4837 --- /dev/null +++ b/live/Demos/Common.cs @@ -0,0 +1,336 @@ +using System.Text.Json.Nodes; +using AngouriMath; +using AngouriMath.Core; +using static AngouriMath.Entity; + +namespace AmLive; + +/// What every demo needs: reading a formula, real numbers out of results, and JSON for the page. +internal static class Common +{ + /// Parses the text, or says why it is not a formula yet. + public static Entity? Parse(string text, out string error) + { + error = ""; + if (string.IsNullOrWhiteSpace(text)) + { + error = "Type a formula."; + return null; + } + try + { + return MathS.FromString(text); + } + catch (Exception e) + { + error = $"Could not read the formula: {e.Message}"; + return null; + } + } + + // Differentiating can attach "provided ..." for a domain no real input leaves; a shader or a + // plot cannot state it, so the demos drop it where they say why. + public static Entity Unconditional(Entity e) => e is Providedf p ? p.Expression : e; + + public static string Latex(Entity? e) + { + if (e is null) + return ""; + try + { + return e.Latexize(); + } + catch (Exception) + { + return ""; + } + } + + /// The real value of a closed expression, or null when it has none. + public static double? Real(Entity e) + { + try + { + if (e is Providedf p) + { + if (p.Predicate.Evaled is not Entity.Boolean { Value: true }) + return null; + e = p.Expression; + } + var z = e.EvalNumerical().ToNumerics(); + if (!double.IsFinite(z.Real)) + return null; + return Math.Abs(z.Imaginary) <= 1e-9 * Math.Max(1, Math.Abs(z.Real)) ? z.Real : null; + } + catch (Exception) + { + return null; + } + } + + /// Like , but infinities count: interval ends can be ±oo. + public static double? RealOrInfinite(Entity e) + { + try + { + var z = e.EvalNumerical().ToNumerics(); + if (double.IsNaN(z.Real) || (double.IsFinite(z.Real) && Math.Abs(z.Imaginary) > 1e-9 * Math.Max(1, Math.Abs(z.Real)))) + return null; + return z.Real; + } + catch (Exception) + { + return null; + } + } + + /// Samples a compiled function of one variable; NaN where it has no real value. + public static double[] Sample(FastExpression? f, double from, double to, int n) + { + var r = new double[n]; + for (var i = 0; i < n; i++) + { + if (f is null) + { + r[i] = double.NaN; + continue; + } + var x = from + (to - from) * i / (n - 1); + try + { + var z = f.Call(x); + r[i] = Math.Abs(z.Imaginary) <= 1e-9 * Math.Max(1, Math.Abs(z.Real)) ? z.Real : double.NaN; + } + catch (Exception) + { + r[i] = double.NaN; + } + } + return r; + } + + public static FastExpression? TryCompile(Entity? e, params Variable[] vars) + { + if (e is null) + return null; + try + { + return e.Compile(vars); + } + catch (Exception) + { + return null; + } + } + + public static T? Try(Func f) where T : class + { + try + { + return f(); + } + catch (Exception) + { + return null; + } + } + + public static JsonArray Numbers(IEnumerable values) + { + var a = new JsonArray(); + foreach (var v in values) + a.Add(double.IsFinite(v) ? JsonValue.Create(v) : null); + return a; + } + + public static JsonArray Strings(IEnumerable values) + { + var a = new JsonArray(); + foreach (var v in values) + a.Add(JsonValue.Create(v)); + return a; + } + + public static string Fail(string error) => new JsonObject { ["ok"] = false, ["error"] = error }.ToJsonString(); + + /// The variables of an expression, sorted by name. + public static List VarsOf(Entity e) => e.Vars.OrderBy(v => v.Name, StringComparer.Ordinal).ToList(); + + /// + /// The formula with e, pi and i read as letters. The parser makes e and pi constants and i + /// the imaginary unit, but a binder that names one of them binds an ordinary variable of that + /// name (AngouriMath's Binding, #984), and among true-or-false letters that is what + /// they are. A set builder is the binder at hand: its Var is that variable. + /// + public static Entity AsLetters(Entity e) => + e.Replace(node => node is Constant || node is Number.Complex && node == MathS.i + ? new Entity.Set.ConditionalSet(node, true).Var + : node); + + /// Generated statements as a function body, indented. + public static string Body(string code) => + string.Concat(code.Split('\n').Where(l => l.Length > 0).Select(l => $" {l}\n")); + + /// Real points of a solution set within [lo, hi], including the members of a family of roots near index 0. + public static List RealPoints(Entity? set, double lo, double hi) + { + var points = new List(); + void Add(double? v) + { + if (v is { } x && x >= lo && x <= hi && !points.Any(p => Math.Abs(p - x) < 1e-9 * Math.Max(1, Math.Abs(x)))) + points.Add(x); + } + var depth = 0; + void Walk(Entity s) + { + switch (s) + { + case Entity.Set.FiniteSet fs: + foreach (var el in fs) + Add(Real(el)); + break; + case Entity.Set.Unionf u: + Walk(u.Left); + Walk(u.Right); + break; + // A family of roots, union({ 2 pi n }, n in ZZ): its members for the indexes near 0. One + // family inside another gets a shorter reach, so the two stay a few thousand members. + case Entity.Set.IndexedUnionf { Over: Entity.Set over } family: + var reach = depth > 0 || family.Body.Nodes.Any(n => n is Entity.Set.IndexedUnionf) ? 20 : 80; + depth++; + for (var n = -reach; n <= reach; n++) + if (over.TryContains(n, out var inside) && inside) + Walk(family.Body.Substitute(family.Var, n)); + depth--; + break; + } + } + if (set is not null) + Walk(set); + points.Sort(); + return points; + } + + /// A set of reals as intervals and points, or null when it is not one the page can draw. + public static JsonArray? Intervals(Entity set) + { + var parts = new JsonArray(); + bool Walk(Entity s) + { + switch (s) + { + case Entity.Set.Interval i: + var lo = RealOrInfinite(i.Left); + var hi = RealOrInfinite(i.Right); + if (lo is null || hi is null) + return false; + parts.Add(new JsonObject + { + ["lo"] = double.IsFinite(lo.Value) ? lo.Value : null, + ["hi"] = double.IsFinite(hi.Value) ? hi.Value : null, + ["loClosed"] = i.LeftClosed, ["hiClosed"] = i.RightClosed, + ["loText"] = i.Left.ToString(), ["hiText"] = i.Right.ToString(), + }); + return true; + case Entity.Set.FiniteSet fs: + foreach (var el in fs) + { + if (Real(el) is not { } v) + return false; + parts.Add(new JsonObject { ["point"] = v, ["text"] = el.ToString() }); + } + return true; + case Entity.Set.Unionf u: + return Walk(u.Left) && Walk(u.Right); + // Points taken out, as the inequality solver takes out where a denominator is zero: + // (-2; 2) \ { 0 } is drawn as (-2; 0) and (0; 2). + case Entity.Set.SetMinusf { Right: Entity.Set.FiniteSet removed } m: + var start = parts.Count; + if (!Walk(m.Left)) + return false; + foreach (var el in removed) + { + if (Real(el) is not { } p) + return false; + for (var k = parts.Count - 1; k >= start; k--) + { + var part = parts[k]!.AsObject(); + if (part["point"] is { } point) + { + if (point.GetValue() == p) + parts.RemoveAt(k); + continue; + } + var from = part["lo"]?.GetValue() ?? double.NegativeInfinity; + var to = part["hi"]?.GetValue() ?? double.PositiveInfinity; + if (p < from || p > to) + continue; + if (p == from) + part["loClosed"] = false; + else if (p == to) + part["hiClosed"] = false; + else + { + parts.Insert(k + 1, new JsonObject + { + ["lo"] = p, ["hi"] = part["hi"]?.DeepClone(), + ["loClosed"] = false, ["hiClosed"] = part["hiClosed"]!.DeepClone(), + ["loText"] = el.ToString(), ["hiText"] = part["hiText"]!.DeepClone(), + }); + part["hi"] = p; + part["hiClosed"] = false; + part["hiText"] = el.ToString(); + } + } + } + return true; + case Entity.Set.SpecialSet when s.ToString() == "RR": + parts.Add(new JsonObject + { + ["lo"] = null, ["hi"] = null, ["loClosed"] = false, ["hiClosed"] = false, + ["loText"] = "-oo", ["hiText"] = "+oo", + }); + return true; + default: + return false; + } + } + return Walk(set) ? parts : null; + } + + private static readonly Dictionary Symbols = new() + { + ["Sumf"] = "+", ["Minusf"] = "−", ["Mulf"] = "×", ["Divf"] = "÷", ["Powf"] = "^", ["Andf"] = "and", + ["Orf"] = "or", ["Xorf"] = "xor", ["Notf"] = "not", ["Impliesf"] = "implies", ["Equalsf"] = "=", + ["Lessf"] = "<", ["Greaterf"] = ">", ["LessOrEqualf"] = "≤", ["GreaterOrEqualf"] = "≥", ["Unionf"] = "∪", + ["Intersectionf"] = "∩", ["SetMinusf"] = "∖", ["Providedf"] = "provided", ["Logf"] = "log", + }; + + /// The expression tree as nested JSON, cut off after nodes. + public static JsonObject Tree(Entity e, ref int budget) + { + budget--; + var name = e.GetType().Name; + var label = e switch + { + Variable or Number or Entity.Boolean => e.ToString(), + _ when Symbols.TryGetValue(name, out var s) => s, + _ => name.EndsWith('f') ? name[..^1].ToLowerInvariant() : name, + }; + var node = new JsonObject { ["t"] = label }; + if (e is Variable or Number or Entity.Boolean) + return node; + var children = new JsonArray(); + foreach (var c in e.DirectChildren) + { + if (budget <= 0) + { + children.Add(new JsonObject { ["t"] = "…" }); + break; + } + children.Add(Tree(c, ref budget)); + } + node["c"] = children; + return node; + } +} diff --git a/live/Demos/Logic.cs b/live/Demos/Logic.cs new file mode 100644 index 0000000000..fa86f204d3 --- /dev/null +++ b/live/Demos/Logic.cs @@ -0,0 +1,221 @@ +using System.Text.Json.Nodes; +using AngouriMath; +using static AngouriMath.Entity; + +namespace AmLive; + +/// +/// The logic demo: a boolean formula as a truth table, a Karnaugh map with its groups, a gate +/// circuit, AngouriMath's simplification and a minimal sum of products, each checked equivalent +/// to the formula by AngouriMath's own truth table. Set formulas over A, B and C are read as the +/// same algebra and drawn as a Venn diagram. +/// +public static class Logic +{ + public static string Analyze(string text) + { + var e = Common.Parse(text, out var error); + if (e is null) + return Common.Fail(error); + e = Common.AsLetters(e); + if (!Representations.IsLogic(e)) + return Common.Fail("Use letters joined by and, or, xor, implies and not, for example (a and b) or not c."); + return Describe(e).ToJsonString(); + } + + /// A formula over sets A, B and C, read as logic: in A ∪ B is in A or in B. + public static string Venn(string text) + { + var e = Common.Parse(text, out var error); + if (e is null) + return Common.Fail(error); + var logic = AsLogic(e); + if (logic is null) + return Common.Fail(@"Use the sets A, B and C with \/ (union), /\ (intersection) and \ (minus), for example (A \/ B) \ C."); + var o = Describe(logic); + if (o["simplified"] is JsonValue simplifiedText && Common.Parse(simplifiedText.GetValue(), out _) is { } s) + o["simplifiedSets"] = AsSets(s); + o["sets"] = AsSets(logic); + return o.ToJsonString(); + } + + private static JsonObject Describe(Entity e) + { + var vars = Common.VarsOf(e); + if (vars.Count == 0 || vars.Count > 6) + return new JsonObject { ["ok"] = false, ["error"] = "Use between one and six variables." }; + + var o = new JsonObject { ["ok"] = true, ["latex"] = Common.Latex(e), ["text"] = e.ToString() }; + var truth = Representations.TruthTable(e, vars); + o["truth"] = truth; + + // The rows where the formula holds, as indices: bit i (from the left) is variable i. + var rows = (JsonArray)truth["rows"]!; + var minterms = new List(); + for (var r = 0; r < rows.Count; r++) + { + var row = (JsonArray)rows[r]!; + if (row[vars.Count]!.GetValue()) + { + var index = 0; + for (var i = 0; i < vars.Count; i++) + index = index * 2 + (row[i]!.GetValue() ? 1 : 0); + minterms.Add(index); + } + } + + var simplified = Common.Try(() => e.Simplify()); + o["simplified"] = simplified?.ToString() ?? ""; + o["simplifiedLatex"] = Common.Latex(simplified); + o["simplifiedEquivalent"] = simplified is not null && Equivalent(e, simplified, vars); + if (simplified is not null) + { + var budget = 80; + o["circuit"] = Common.Tree(simplified, ref budget); + } + + var cover = MinimalCover(minterms, vars.Count); + var sop = SumOfProducts(cover, vars); + o["groups"] = new JsonArray(cover.Select(c => (JsonNode)new JsonObject { ["mask"] = c.Mask, ["value"] = c.Value }).ToArray()); + o["sop"] = sop.ToString(); + o["sopLatex"] = Common.Latex(sop); + o["sopEquivalent"] = Equivalent(e, sop, vars); + return o; + } + + /// AngouriMath's truth table of "a xor b" has no true row exactly when a and b agree everywhere. + internal static bool Equivalent(Entity a, Entity b, List vars) => NeverTrue(a.Xor(b), vars); + + /// Whether AngouriMath's truth table of the formula has no true row. + internal static bool NeverTrue(Entity e, List vars) + { + var table = Common.Try(() => MathS.Boolean.BuildTruthTable(e, vars.ToArray())); + if (table is null) + return false; + for (var i = 0; i < table.RowCount; i++) + if (table[i, table.ColumnCount - 1] is Entity.Boolean { Value: true }) + return false; + return true; + } + + /// A product term: the variables whose bit is set in Mask, each fixed to its bit in Value. + internal readonly record struct Term(int Mask, int Value) + { + public bool Covers(int minterm) => (minterm & Mask) == Value; + public int Literals => System.Numerics.BitOperations.PopCount((uint)Mask); + } + + // Quine–McCluskey: merge terms that differ in one bit until nothing merges; what never merged + // is prime. Then the smallest set of primes covering every minterm, by search over sizes, + // fewest literals breaking ties. Six variables give at most 64 minterms. Don't-cares, rows + // that cannot occur, take part in the merging but need no cover. + internal static List MinimalCover(List minterms, int n, IReadOnlyCollection? dontCares = null) + { + dontCares ??= []; + var full = (1 << n) - 1; + if (minterms.Count == 0) + return new(); + if (minterms.Count + dontCares.Count == 1 << n) + return new() { new Term(0, 0) }; + var current = minterms.Concat(dontCares).Select(m => new Term(full, m)).ToHashSet(); + var primes = new HashSet(); + while (current.Count > 0) + { + var next = new HashSet(); + var merged = new HashSet(); + var list = current.ToList(); + for (var i = 0; i < list.Count; i++) + for (var j = i + 1; j < list.Count; j++) + { + var (a, b) = (list[i], list[j]); + var diff = a.Value ^ b.Value; + if (a.Mask == b.Mask && System.Numerics.BitOperations.PopCount((uint)diff) == 1) + { + next.Add(new Term(a.Mask & ~diff, a.Value & ~diff)); + merged.Add(a); + merged.Add(b); + } + } + primes.UnionWith(current.Where(t => !merged.Contains(t))); + current = next; + } + + var primeList = primes.Where(p => minterms.Any(p.Covers)).OrderByDescending(p => (1 << n) - p.Literals).ToList(); + var essential = primeList.Where(p => minterms.Any(m => p.Covers(m) && primeList.Count(q => q.Covers(m)) == 1)).ToList(); + var left = minterms.Where(m => !essential.Any(p => p.Covers(m))).ToList(); + var candidates = primeList.Except(essential).Where(p => left.Any(p.Covers)).ToList(); + for (var size = 0; size <= candidates.Count; size++) + { + List? best = null; + foreach (var pick in Combinations(candidates, size)) + if (left.All(m => pick.Any(p => p.Covers(m))) && + (best is null || pick.Sum(p => p.Literals) < best.Sum(p => p.Literals))) + best = pick; + if (best is not null) + return essential.Concat(best).ToList(); + } + return primeList; + } + + private static IEnumerable> Combinations(List items, int size, int start = 0) + { + if (size == 0) + { + yield return new(); + yield break; + } + for (var i = start; i <= items.Count - size; i++) + foreach (var rest in Combinations(items, size - 1, i + 1)) + { + rest.Insert(0, items[i]); + yield return rest; + } + } + + internal static Entity SumOfProducts(List cover, List vars) + { + if (cover.Count == 0) + return false; + Entity? sum = null; + foreach (var term in cover) + { + Entity? product = null; + for (var i = 0; i < vars.Count; i++) + { + var bit = 1 << (vars.Count - 1 - i); + if ((term.Mask & bit) == 0) + continue; + Entity literal = (term.Value & bit) != 0 ? vars[i] : !vars[i]; + product = product is null ? literal : product & literal; + } + product ??= true; + sum = sum is null ? product : sum | product; + } + return sum!; + } + + private static Entity? AsLogic(Entity e) => e switch + { + Variable v when v.Name is "A" or "B" or "C" => v, + Entity.Set.Unionf u when AsLogic(u.Left) is { } l && AsLogic(u.Right) is { } r => l | r, + Entity.Set.Intersectionf i when AsLogic(i.Left) is { } l && AsLogic(i.Right) is { } r => l & r, + Entity.Set.SetMinusf m when AsLogic(m.Left) is { } l && AsLogic(m.Right) is { } r => l & !r, + _ => null, + }; + + private static string AsSets(Entity e) => e switch + { + Variable v => v.Name, + Entity.Boolean { Value: true } => "everything", + Entity.Boolean => "∅", + Orf o => $"{Wrap(o.Left)} ∪ {Wrap(o.Right)}", + Andf { Right: Notf n } a => $"{Wrap(a.Left)} ∖ {Wrap(n.Argument)}", + Andf { Left: Notf n } a => $"{Wrap(a.Right)} ∖ {Wrap(n.Argument)}", + Andf a => $"{Wrap(a.Left)} ∩ {Wrap(a.Right)}", + Notf n => $"the complement of {Wrap(n.Argument)}", + Xorf x => $"{Wrap(x.Left)} △ {Wrap(x.Right)}", + _ => e.ToString(), + }; + + private static string Wrap(Entity e) => e is Variable ? AsSets(e) : $"({AsSets(e)})"; +} diff --git a/live/Demos/Matrices.cs b/live/Demos/Matrices.cs new file mode 100644 index 0000000000..5089c278dc --- /dev/null +++ b/live/Demos/Matrices.cs @@ -0,0 +1,244 @@ +using System.Text.Json.Nodes; +using AngouriMath; +using static AngouriMath.Entity; + +namespace AmLive; + +/// +/// The matrices demo: a matrix written as AngouriMath reads it, [[1, 2], [3, 4]], and what the +/// library gives for it: the transpose, determinant, trace, rank, inverse and reduced row echelon +/// form; the characteristic polynomial det(A - λI) and its roots, the eigenvalues; and each +/// eigenvalue's eigenvectors, read off the reduced row echelon form of A - λI. With a second +/// matrix, the product and the tensor product. +/// +public static class Matrices +{ + private const int Largest = 6; + private static readonly Variable Lambda = "lambda"; + private static Matrix? last; + + public static string Analyze(string aText, string bText) + { + var a = Read(aText, "A", out var error); + if (a is null) + return Common.Fail(error); + last = a; + var numeric = !a.Vars.Any(); + var o = new JsonObject + { + ["ok"] = true, + ["latex"] = Common.Latex(a), + ["text"] = a.ToString(), + ["rows"] = a.RowCount, + ["cols"] = a.ColumnCount, + ["numeric"] = numeric, + ["transpose"] = Common.Latex(a.T), + }; + try + { + o["rank"] = a.Rank; + } + catch (Exception) + { + } + // With letters, for their values in general: a pivot that is a formula is divided by, and + // the conditions that come with it are stated. + var rrefConditions = new HashSet(); + o["rref"] = Common.Latex(Common.Try(() => Tidy(a.ReducedRowEchelonForm, rrefConditions))); + o["rrefConditions"] = Common.Strings(rrefConditions); + + if (a.IsSquare) + { + var determinant = Common.Try(() => a.Determinant?.Simplify()); + o["det"] = Common.Latex(determinant); + o["trace"] = Common.Latex(Common.Try(() => a.Trace.Simplify())); + var conditions = new HashSet(); + var inverse = Common.Try(() => a.Inverse is { } inv ? Tidy(inv, conditions) : null); + o["inverse"] = Common.Latex(inverse); + o["inverseConditions"] = Common.Strings(conditions); + Eigen(a, numeric, o); + } + if (a.RowCount == 2 && a.ColumnCount == 2 && numeric) + o["entries"] = Common.Numbers(new[] { a[0, 0], a[0, 1], a[1, 0], a[1, 1] }.Select(x => Common.Real(x) ?? double.NaN)); + + if (!string.IsNullOrWhiteSpace(bText)) + { + var b = Read(bText, "B", out var bError); + if (b is null) + o["bError"] = bError; + else + { + o["b"] = Common.Latex(b); + if (a.ColumnCount == b.RowCount) + o["product"] = Common.Latex(Common.Try(() => ((Entity)a * b).Evaled is Matrix p ? Tidy(p) : null)); + else + o["productNote"] = $"A has {a.ColumnCount} columns and B has {b.RowCount} rows, so A B is not defined."; + o["tensor"] = Common.Latex(Common.Try(() => Tidy(Matrix.TensorProduct(a, b)))); + } + } + return o.ToJsonString(); + } + + /// The last matrix to the power n; a negative power goes through the inverse. + public static string Power(int n) + { + if (last is null || !last.IsSquare) + return Common.Fail("Powers are of square matrices."); + var power = Common.Try(() => MathS.Pow(last, n).Evaled is Matrix p ? Tidy(p) : null); + return power is null + ? Common.Fail(n < 0 ? "This matrix has no inverse, so no negative powers." : "AngouriMath did not find this power.") + : new JsonObject { ["ok"] = true, ["latex"] = Common.Latex(power) }.ToJsonString(); + } + + /// The matrix the text is, or evaluates to (jacobian(...) and hessian(...) do). + private static Matrix? Read(string text, string name, out string error) + { + var e = Common.Parse(text, out error); + if (e is null) + return null; + var m = e as Matrix ?? Common.Try(() => e.Evaled) as Matrix; + if (m is null) + { + error = $"Write {name} row by row, as [[1, 2], [3, 4]]."; + return null; + } + if (m.RowCount > Largest || m.ColumnCount > Largest) + { + error = $"{name} is {m.RowCount} by {m.ColumnCount}; this page takes up to {Largest} by {Largest}."; + return null; + } + // jacobian and hessian leave their derivatives to be taken. + return m.Nodes.Any(n => n is Derivativef) ? Tidy(m) : m; + } + + /// + /// The characteristic polynomial, its roots, and for a matrix of numbers each eigenvalue's + /// eigenvectors: the null space of A - λI, one vector per column without a pivot in its + /// reduced row echelon form. + /// + private static void Eigen(Matrix a, bool numeric, JsonObject o) + { + var shifted = a.With((i, j, e) => i == j ? e - Lambda : e); + var polynomial = Common.Try(() => shifted.Determinant?.Simplify()); + if (polynomial is null) + return; + o["charpoly"] = Common.Latex(polynomial); + // Past 2 by 2 the roots of a polynomial with letters in it are pages long. + if (!numeric && a.RowCount > 2) + return; + if (Common.Try(() => polynomial.SolveEquation(Lambda)) is not Entity.Set.FiniteSet roots) + return; + var eigen = new JsonArray(); + foreach (var root in roots) + { + var value = Common.Try(() => root.Simplify()) ?? root; + var full = Common.Latex(value); + var latex = Short(value); + var item = new JsonObject { ["latex"] = latex }; + if (numeric) + { + var number = Common.Try(() => value.EvalNumerical()); + var c = number?.ToNumerics(); + item["approx"] = c is { } w ? Approx(w) : ""; + item["re"] = c?.Real; + item["im"] = c?.Imaginary; + var vectors = new JsonArray(); + // A root of a cubic comes by Cardano's formula, through cube roots, and eliminating + // with it exactly takes seconds; its eigenvectors are found from its value instead. + var exact = latex != "" && !full.Contains(@"\sqrt["); + Entity? at = exact ? value : number; + var reduced = at is null ? null : Common.Try(() => + { + var m = shifted.With((i, j, e) => e.Substitute(Lambda, at)); + return exact ? Tidy(Tidy(m).ReducedRowEchelonForm) : m.With((i, j, e) => e.Evaled).ReducedRowEchelonForm; + }); + if (reduced is not null) + foreach (var v in NullSpace(reduced)) + { + var parts = v.Select(x => Common.Try(() => x.EvalNumerical())).ToList(); + vectors.Add(new JsonObject + { + ["latex"] = exact ? Short(MathS.Vector(v)) : "", + ["numeric"] = parts.All(p => p is not null && Math.Abs(p.ToNumerics().Imaginary) < 1e-12) + ? Common.Numbers(parts.Select(p => p!.ToNumerics().Real)) + : null, + }); + } + item["vectors"] = vectors; + } + eigen.Add(item); + } + o["eigen"] = eigen; + } + + private static List NullSpace(Matrix reduced) + { + var n = reduced.ColumnCount; + var pivots = new List<(int Row, int Column)>(); + for (var r = 0; r < reduced.RowCount; r++) + for (var c = 0; c < n; c++) + if (!IsZero(reduced[r, c])) + { + pivots.Add((r, c)); + break; + } + var vectors = new List(); + for (var free = 0; free < n; free++) + { + if (pivots.Any(p => p.Column == free)) + continue; + var v = Enumerable.Repeat((Entity)0, n).ToArray(); + v[free] = 1; + foreach (var (row, column) in pivots) + v[column] = Common.Try(() => (-reduced[row, free]).Simplify()) ?? -reduced[row, free]; + vectors.Add(v); + } + return vectors; + } + + private static bool IsZero(Entity e) + { + try + { + return e.EvalNumerical().ToNumerics().Magnitude < 1e-9; + } + catch (Exception) + { + return false; + } + } + + /// + /// Simplified entry by entry. A condition an entry comes with ("provided not a = 0") is taken + /// off and collected, so that the matrix reads plainly and its conditions are stated once. + /// + private static Matrix Tidy(Matrix m, HashSet? conditions = null) => + m.With((i, j, e) => + { + var s = Common.Try(() => e.Simplify()) ?? e; + if (s is Providedf p) + { + conditions?.Add(Common.Latex(p.Predicate)); + return p.Expression; + } + return s; + }); + + // Cubic roots by Cardano's formula run to pages; past this a numeric value stands in. + private static string Short(Entity e) + { + var latex = Common.Latex(e); + return latex.Length <= 400 ? latex : ""; + } + + private static string Approx(System.Numerics.Complex c) + { + static string F(double x) => Math.Round(x, 6).ToString("0.######", System.Globalization.CultureInfo.InvariantCulture); + if (Math.Abs(c.Imaginary) < 1e-12) + return F(c.Real); + var imaginary = Math.Abs(c.Imaginary) == 1 ? "i" : $"{F(Math.Abs(c.Imaginary))}i"; + if (Math.Abs(c.Real) < 1e-12) + return c.Imaginary < 0 ? $"-{imaginary}" : imaginary; + return $"{F(c.Real)} {(c.Imaginary < 0 ? "-" : "+")} {imaginary}"; + } +} diff --git a/live/Demos/Motion.cs b/live/Demos/Motion.cs new file mode 100644 index 0000000000..87849a0e7b --- /dev/null +++ b/live/Demos/Motion.cs @@ -0,0 +1,211 @@ +using System.Diagnostics; +using System.Numerics; +using System.Text.Json.Nodes; +using AngouriMath; +using AngouriMath.Core; +using static AngouriMath.Entity; + +namespace AmLive; + +/// +/// The motion demo: from a Lagrangian L (kinetic minus potential energy) in one or two +/// coordinates, AngouriMath checks that L is an energy, derives the Euler–Lagrange equations, +/// solves them for the accelerations, and derives the conserved energy. The page then integrates +/// the motion here, and draws the energy's level curves (the phase portrait) on the GPU. +/// +public static class Motion +{ + private static readonly Dimension M = Dimension.Mass, L = Dimension.Length, T = Dimension.Time; + private static readonly Dimension Energy = M * L.Pow(2) / T.Pow(2); + + private static readonly Dictionary ParameterDims = new() + { + ["m"] = M, ["m_1"] = M, ["m_2"] = M, + ["l"] = L, ["l_1"] = L, ["l_2"] = L, ["l_0"] = L, + ["g"] = L / T.Pow(2), ["k"] = M / T.Pow(2), + }; + + // The mass matrix row by row, then the force vector: M a = F. + private static FastExpression[] terms = Array.Empty(); + private static FastExpression? energy; + private static int dof; + + /// + /// Derives the motion. Coordinates are angles or lengths (), each + /// with its rate of change; parameters are fixed to the given values for the simulation. + /// + public static string Derive(string lagrangian, string[] coords, string[] rates, string[] kinds, + string[] parameters, double[] values) + { + var clock = Stopwatch.StartNew(); + var lag = Common.Parse(lagrangian, out var error); + if (lag is null) + return Common.Fail(error); + var n = coords.Length; + var q = coords.Select(c => (Variable)c).ToArray(); + var w = rates.Select(r => (Variable)r).ToArray(); + + var dims = new Dictionary(ParameterDims); + for (var i = 0; i < n; i++) + { + dims[q[i]] = kinds[i] == "length" ? L : Dimension.Dimensionless; + dims[w[i]] = dims[q[i]] / T; + } + var check = MathS.Dimensions.Of(lag, dims); + if (!check.IsConsistent) + return Common.Fail($"The units check failed. {check}"); + if (!check.Dimension!.Equals(Energy)) + return Common.Fail($"A Lagrangian is an energy, M L^2 T^-2, but this one has dimension {check.Dimension}."); + + // Euler–Lagrange, d/dt(dL/dw_i) = dL/dq_i, is linear in the accelerations: M a = F, with + // M_ij = d^2L/dw_i dw_j and F_i = dL/dq_i - sum_j d^2L/dw_i dq_j w_j. The entries stay + // small enough to simplify; the solved accelerations do not (36 s for the double + // pendulum), so the 2 by 2 system is solved numerically at every step instead. + Entity D(Entity e, Variable v) => Common.Unconditional(e.Differentiate(v)); + var momentum = w.Select(r => D(lag, r)).ToArray(); + var mass = new Entity[n, n]; + var force = new Entity[n]; + for (var i = 0; i < n; i++) + { + for (var j = 0; j < n; j++) + mass[i, j] = Tidy(D(momentum[i], w[j])); + Entity f = D(lag, q[i]); + for (var j = 0; j < n; j++) + f -= D(momentum[i], q[j]) * w[j]; + force[i] = Tidy(f); + } + Entity hamiltonian = -lag; + for (var i = 0; i < n; i++) + hamiltonian += w[i] * momentum[i]; + hamiltonian = Tidy(hamiltonian); + + Entity Numeric(Entity e) + { + for (var i = 0; i < parameters.Length; i++) + e = e.Substitute(parameters[i], values[i]); + return e; + } + var order = q.Concat(w).ToArray(); + var compiled = new FastExpression?[n * n + n]; + for (var i = 0; i < n; i++) + { + for (var j = 0; j < n; j++) + compiled[i * n + j] = Common.TryCompile(Numeric(mass[i, j]), order); + compiled[n * n + i] = Common.TryCompile(Numeric(force[i]), order); + } + var compiledEnergy = Common.TryCompile(Numeric(hamiltonian), order); + if (compiled.Any(c => c is null) || compiledEnergy is null) + return Common.Fail("The equations of motion use something the numeric compiler does not support."); + terms = compiled!; + energy = compiledEnergy; + dof = n; + + string Matrix(IEnumerable> rows) => + "\\begin{pmatrix}" + string.Join(" \\\\ ", rows.Select(r => string.Join(" & ", r))) + "\\end{pmatrix}"; + var accelerationsLatex = Matrix(q.Select(v => new[] { $"\\ddot{{{Common.Latex(v)}}}" })); + var equation = n == 1 + ? $"{Common.Latex(mass[0, 0])} \\, \\ddot{{{Common.Latex(q[0])}}} = {Common.Latex(force[0])}" + : $"{Matrix(Enumerable.Range(0, n).Select(i => Enumerable.Range(0, n).Select(j => Common.Latex(mass[i, j]))))} " + + $"{accelerationsLatex} = {Matrix(force.Select(f => new[] { Common.Latex(f) }))}"; + var result = new JsonObject + { + ["ok"] = true, + ["units"] = check.ToString(), + ["lagrangian"] = Common.Latex(lag), + ["equation"] = equation, + ["energy"] = Common.Latex(hamiltonian), + ["ms"] = clock.ElapsedMilliseconds, + }; + // As AngouriMath writes a matrix, for the Matrices tab to read back. + if (n > 1) + result["mass"] = MathS.Matrix(mass).ToString(); + if (n == 1) + { + var source = MathS.Shaders.Glsl(new List> { new("e", Numeric(hamiltonian)) }, + new Dictionary { [q[0]] = "p.x", [w[0]] = "p.y" }); + if (source.Succeeded) + result["energyGlsl"] = $"float energy(vec2 p)\n{{\n float e;\n{Common.Body(source.Code!)} return e;\n}}\n"; + } + return result.ToJsonString(); + } + + /// + /// Advances every copy of the system (coordinates then rates, copy after copy) by + /// classical Runge–Kutta steps of . + /// + public static double[] Step(double[] state, double dt, int steps) + { + var s = (double[])state.Clone(); + var size = 2 * dof; + if (size == 0) + return s; + var y = new double[size]; + var k = new double[4][]; + for (var c = 0; c + size <= s.Length; c += size) + { + Array.Copy(s, c, y, 0, size); + for (var step = 0; step < steps; step++) + { + k[0] = Rate(y); + k[1] = Rate(Add(y, k[0], dt / 2)); + k[2] = Rate(Add(y, k[1], dt / 2)); + k[3] = Rate(Add(y, k[2], dt)); + for (var i = 0; i < size; i++) + y[i] += dt / 6 * (k[0][i] + 2 * k[1][i] + 2 * k[2][i] + k[3][i]); + } + Array.Copy(y, 0, s, c, size); + } + return s; + } + + /// The conserved energy of every copy. + public static double[] Energies(double[] state) + { + var size = 2 * dof; + if (size == 0 || energy is null) + return Array.Empty(); + var result = new double[state.Length / size]; + for (var c = 0; c < result.Length; c++) + result[c] = energy.Call(Args(state, c * size, size)).Real; + return result; + } + + private static double[] Rate(double[] y) + { + var r = new double[y.Length]; + var args = Args(y, 0, y.Length); + var v = terms.Select(t => t.Call(args).Real).ToArray(); + for (var i = 0; i < dof; i++) + r[i] = y[dof + i]; + if (dof == 1) + r[1] = v[1] / v[0]; + else + { + // Cramer's rule on M a = F, with M = [v0 v1; v2 v3] and F = [v4 v5]. + var det = v[0] * v[3] - v[1] * v[2]; + r[2] = (v[4] * v[3] - v[1] * v[5]) / det; + r[3] = (v[0] * v[5] - v[2] * v[4]) / det; + } + return r; + } + + // Simplifies what is small enough to simplify quickly; leaves the rest as derived. + private static Entity Tidy(Entity e) => + e.Nodes.Count() <= 120 ? Common.Try(() => e.Simplify()) ?? e : e; + + private static double[] Add(double[] y, double[] k, double h) + { + var r = new double[y.Length]; + for (var i = 0; i < y.Length; i++) + r[i] = y[i] + h * k[i]; + return r; + } + + private static Complex[] Args(double[] s, int from, int count) + { + var a = new Complex[count]; + for (var i = 0; i < count; i++) + a[i] = s[from + i]; + return a; + } +} diff --git a/live/Demos/Numbers.cs b/live/Demos/Numbers.cs new file mode 100644 index 0000000000..6d0d59409a --- /dev/null +++ b/live/Demos/Numbers.cs @@ -0,0 +1,266 @@ +using System.Diagnostics; +using System.Text; +using System.Text.Json.Nodes; +using AngouriMath; +using AngouriMath.Core.Exceptions; +using PeterO.Numbers; +using static AngouriMath.Entity; +using static AngouriMath.Entity.Number; +using BigInteger = System.Numerics.BigInteger; + +namespace AmLive; + +/// +/// The numbers demo: arithmetic AngouriMath keeps exact (big integers, fractions, roots, complex +/// numbers), decimals to as many digits as asked, primes, factors and divisors, and other bases. +/// +public static class Numbers +{ + // The digits to base 36, as AngouriMath's ToBaseN and FromBaseN have them. + private const string Alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + + // Past this many digits the exact value is shown cut in the middle, not typeset. + private const int LongestTypeset = 1500; + + // Past this many digits an integer is not written in other bases: ToBaseN divides the whole + // number once for each digit it writes, so 3000! takes a second here and 10000! twenty. + private const int LongestInBases = 10_000; + + public static string Describe(string text, int digits, int numberBase, string otherText) + { + var e = Common.Parse(text, out var error); + if (e is null) + return Common.Fail(error); + if (e.Vars.Any()) + return Common.Fail($"Only numbers here; this has {string.Join(", ", Common.VarsOf(e).Select(v => v.Name))}."); + var value = Common.Try(() => e.Evaled); + if (value is not Complex z) + return Common.Fail("This is not a number."); + // A whole number or a fraction is finite at any size; its decimal is not past 10^1000, + // where the precision context's exponents end. A complex part past it is an infinity. + static bool Finite(Real part) => part is Rational || part.EDecimal.IsFinite; + if (z.IsNaN || !Finite(z.RealPart) || !Finite(z.ImaginaryPart)) + return Common.Fail($"This has no finite value: AngouriMath gives {z}."); + + digits = Math.Clamp(digits, 5, 2000); + numberBase = Math.Clamp(numberBase, 2, 36); + var context = new EContext(digits, ERounding.HalfEven, -100_000, 100_000, false); + T InPrecision(Func f) where T : class => + MathS.Settings.DecimalPrecisionContext.As(context, () => Common.Try(f))!; + + var kind = z switch { Integer => "integer", Rational => "rational", Real => "real", _ => "complex" }; + var o = new JsonObject { ["ok"] = true, ["kind"] = kind }; + + // Integers and fractions are already exact; anything else keeps its roots and constants. + var exact = z is Rational ? z : Common.Try(() => e.Simplify()) ?? e; + var exactText = exact.ToString(); + static string Cut(string text) => text.Length > LongestTypeset ? $"{text[..80]} … {text[^80..]}" : text; + o["exactText"] = Cut(exactText); + o["exactLatex"] = exactText.Length > LongestTypeset ? "" : Common.Latex(exact); + var length = z is Integer whole ? BigInteger.Abs(Big(whole)).ToString().Length : 0; + if (length > 0) + o["length"] = length; + + var numeric = z is Rational ? null : InPrecision(() => e.EvalNumerical()); + var period = 0; + // A part that is a fraction is written out exactly, as 0.(142857); any other to the precision. + string Part(Real part) => part is Rational q && q is not Integer + ? Expansion(Big(q.Numerator), Big(q.Denominator), 10, out _) + : part.ToString(); + o["decimal"] = z switch + { + Integer => o["exactText"]!.GetValue(), + Rational q => Expansion(Big(q.Numerator), Big(q.Denominator), 10, out period), + Real => numeric?.ToString() ?? "", + _ when numeric is { } c => c.ImaginaryPart.EDecimal.IsZero + ? Part(c.RealPart) + : $"{Part(c.RealPart)} {(c.ImaginaryPart.EDecimal.IsNegative ? "-" : "+")} {Part((Real)MathS.Abs(c.ImaginaryPart).Evaled)}i", + _ => "", + }; + o["period"] = period; + + // Other bases, by AngouriMath's ToBaseN: an integer exactly, shown cut in the middle as its + // exact value is, and an irrational number cut where the precision ends. A fraction by long + // division here, with its repeating block in brackets: ToBaseN writes the same digits and + // cuts them. + if ((z as Real ?? numeric as Real) is { } real && (z is Rational || real.EDecimal.IsFinite) && length <= LongestInBases) + { + var bases = new JsonArray(); + foreach (var b in new[] { 2, 8, 16, numberBase }.Distinct()) + bases.Add(new JsonObject + { + ["base"] = b, + ["digits"] = z switch + { + Integer => Cut(MathS.ToBaseN(real, b)), + Rational q => Expansion(Big(q.Numerator), Big(q.Denominator), b, out _), + _ => InPrecision(() => MathS.ToBaseN(real, b)) ?? "", + }, + ["exact"] = z is Rational, + }); + o["bases"] = bases; + } + + if (z is Integer n) + { + // Membership of PP is decided by Miller–Rabin, exact below 3317044064679887385961981, + // and by Lucas–Lehmer for 2^p - 1; past that a number that passes stays undecided. + var prime = Common.Try(() => n.In(MathS.Sets.Primes).Evaled); + o["prime"] = prime is Entity.Boolean b ? (b.Value ? "yes" : "no") : "undecided"; + if (Common.Parse(otherText, out _)?.Evaled is Integer m && !m.EInteger.IsZero) + { + var gcd = MathS.NumberTheory.GreatestCommonDivisor(n, m); + Entity lcm = MathS.Abs(n * m / gcd); + Entity ratio = (Entity)n / m; + o["other"] = new JsonObject + { + ["m"] = m.ToString(), + ["gcd"] = gcd.ToString(), + ["lcm"] = lcm.Evaled.ToString(), + ["ratioLatex"] = $"\\frac{{{Common.Latex(n)}}}{{{Common.Latex(m)}}} = {Common.Latex(ratio.Evaled)}", + }; + } + } + + if (z is not Real) + { + // Exact where simplifying finds the part, as for 1/10 + 7/10 i; where it leaves + // Re, Im, |z| or arg standing, the value to twelve digits instead. + var c = z.ToNumerics(); + var (x, y) = (c.Real, c.Imaginary); + // Past the range of a double the plane draws the direction alone: the parts scaled + // down together, as (3 + 4i)^450 is. + if (!double.IsFinite(x) || !double.IsFinite(y)) + { + var (re, im) = (z.RealPart.EDecimal, z.ImaginaryPart.EDecimal); + var larger = re.Abs().CompareTo(im.Abs()) >= 0 ? re.Abs() : im.Abs(); + (x, y) = (re.Divide(larger, EContext.Binary64).ToDouble(), im.Divide(larger, EContext.Binary64).ToDouble()); + } + var parts = new JsonObject { ["x"] = x, ["y"] = y }; + foreach (var (name, part, approx) in new (string, Func, double)[] + { ("re", MathS.Re, c.Real), ("im", MathS.Im, c.Imaginary), ("abs", MathS.Abs, c.Magnitude), ("arg", MathS.Arg, Math.Atan2(y, x)) }) + { + var found = Common.Try(() => part(e).Simplify()); + parts[name] = found is null || found.Nodes.Any(n => n is Ref or Imf or Absf or Argf) + ? $@"\approx {approx.ToString("G12", System.Globalization.CultureInfo.InvariantCulture)}" + : Common.Latex(found); + } + o["complex"] = parts; + } + return o.ToJsonString(); + } + + /// The prime factors of an integer, how many divisors it has and its totient, each by AngouriMath. + public static string Factor(string text) + { + var clock = Stopwatch.StartNew(); + if (Common.Parse(text, out var error)?.Evaled is not Integer n) + return Common.Fail(error == "" ? "Only whole numbers have prime factors." : error); + var size = n.EInteger.Abs(); + if (size.CompareTo(EInteger.FromInt32(2)) < 0) + return Common.Fail($"{n} has no prime factors."); + Integer whole = size; + List<(Integer prime, Integer power)> factors; + Integer count, totient; + try + { + factors = MathS.NumberTheory.Factorize(whole).ToList(); + count = MathS.NumberTheory.CountDivisors(whole); + totient = whole.Phi(); + } + catch (NotSufficientlySupportedException) + { + return Common.Fail("AngouriMath did not factor this: past trial division, a factor is neither proven prime by Miller–Rabin nor split by Pollard’s rho."); + } + + var list = new JsonArray(); + foreach (var (p, k) in factors) + list.Add(new JsonObject { ["p"] = p.ToString(), ["k"] = k.ToString() }); + var latex = string.Join(@" \cdot ", factors.Select(f => f.power == 1 ? f.prime.ToString() : $"{f.prime}^{{{f.power}}}")); + var o = new JsonObject + { + ["ok"] = true, + ["factors"] = list, + ["latex"] = $"{(n.EInteger.Sign < 0 ? "-" : "")}{latex}", + ["divisorCount"] = count.ToString(), + ["totient"] = totient.ToString(), + ["ms"] = clock.ElapsedMilliseconds, + }; + // Every divisor, from the factors, when there are few enough to list. + if (Big(count) <= 96) + { + var divisors = new List { 1 }; + foreach (var (p, k) in factors) + { + var prime = Big(p); + divisors = divisors.SelectMany(d => Enumerable.Range(0, (int)Big(k) + 1).Select(i => d * BigInteger.Pow(prime, i))).ToList(); + } + o["divisors"] = Common.Strings(divisors.Order().Select(d => d.ToString())); + } + return o.ToJsonString(); + } + + /// Digits in a base from 2 to 36 read back as a number, by AngouriMath, which refuses a digit not in the base. + public static string FromBase(string digits, int numberBase) + { + try + { + var value = MathS.FromBaseN(digits.Trim(), numberBase); + return new JsonObject { ["ok"] = true, ["text"] = value.ToString(), ["latex"] = Common.Latex(value) }.ToJsonString(); + } + catch (Exception e) + { + return Common.Fail(e.Message); + } + } + + private static BigInteger Big(Integer n) => BigInteger.Parse(n.EInteger.ToString()); + + /// Whether a fraction with this denominator ends in the base: when every prime of the denominator divides the base. + private static bool Terminates(BigInteger denominator, int numberBase) + { + var d = BigInteger.Abs(denominator); + for (var g = BigInteger.GreatestCommonDivisor(d, numberBase); g > 1; g = BigInteger.GreatestCommonDivisor(d, numberBase)) + while (d % g == 0) + d /= g; + return d == 1; + } + + /// + /// A fraction written out in the base by long division, with the repeating block in brackets, + /// as 0.(142857) for 1/7. The block is found when a remainder comes back; past 1000 digits the + /// expansion is cut. + /// + private static string Expansion(BigInteger numerator, BigInteger denominator, int numberBase, out int period) + { + var sign = numerator.Sign * denominator.Sign < 0 ? "-" : ""; + numerator = BigInteger.Abs(numerator); + denominator = BigInteger.Abs(denominator); + var whole = BigInteger.DivRem(numerator, denominator, out var remainder); + var digits = new StringBuilder(); + var seen = new Dictionary(); + period = 0; + while (remainder != 0 && digits.Length < 1000) + { + if (seen.TryGetValue(remainder, out var start)) + { + period = digits.Length - start; + digits.Insert(start, '(').Append(')'); + break; + } + seen[remainder] = digits.Length; + var digit = BigInteger.DivRem(remainder * numberBase, denominator, out remainder); + digits.Append(Alphabet[(int)digit]); + } + if (remainder != 0 && period == 0) + digits.Append('…'); + var integer = new StringBuilder(); + for (var w = whole; ; w /= numberBase) + { + integer.Insert(0, Alphabet[(int)(w % numberBase)]); + if (w < numberBase) + break; + } + return digits.Length == 0 ? $"{sign}{integer}" : $"{sign}{integer}.{digits}"; + } +} diff --git a/live/Demos/Regions.cs b/live/Demos/Regions.cs new file mode 100644 index 0000000000..c814b9382c --- /dev/null +++ b/live/Demos/Regions.cs @@ -0,0 +1,126 @@ +using System.Diagnostics; +using System.Text.Json.Nodes; +using AngouriMath; +using static AngouriMath.Entity; + +namespace AmLive; + +/// +/// The regions demo. In the plane: a statement in x and y becomes a GPU test of whether a point +/// is inside, each comparison's boundary gets its exact gradient so the page can draw it one +/// pixel wide, the statement is solved for y, and boundaries are intersected exactly. On the +/// line: a statement in x, or a set formula, becomes intervals. +/// +public static class Regions +{ + private const int MaxEdges = 6; + private static readonly Variable X = "x", Y = "y"; + + private static readonly Dictionary Names = new() { ["x"] = "p.x", ["y"] = "p.y" }; + + public static string Analyze(string text) + { + var clock = Stopwatch.StartNew(); + var e = Common.Parse(text, out var error); + if (e is null) + return Common.Fail(error); + var stray = e.Vars.Where(v => v != X && v != Y).Select(v => v.Name).ToList(); + if (stray.Count > 0) + return Common.Fail($"Use x and y only. This formula also has {string.Join(", ", stray)}."); + + if (e is Entity.Set || !e.Vars.Contains(Y)) + return Line(e, clock); + if (e is not Statement) + return Common.Fail("Type a comparison, such as x^2 + y^2 < 1 or y > sin(x)."); + + var inside = MathS.Shaders.Glsl(new List> { new("inside", e) }, Names); + if (!inside.Succeeded) + return Common.Fail(inside.ToString()); + + var comparisons = e.Nodes.OfType().Distinct().Take(MaxEdges).ToList(); + var edges = new JsonArray(); + var boundaries = new List(); + var glsl = $"bool regionInside(vec2 p)\n{{\n bool inside;\n{Common.Body(inside.Code!)} return inside;\n}}\n"; + foreach (var c in comparisons) + { + if (c.DirectChildren.ToList() is not [var left, var right]) + continue; + var g = left - right; + var outputs = new List> + { + new("r.x", g), + new("r.y", Common.Unconditional(g.Differentiate(X))), + new("r.z", Common.Unconditional(g.Differentiate(Y))), + }; + var source = MathS.Shaders.Glsl(outputs, Names); + if (!source.Succeeded) + continue; + glsl += $"\nvec3 edge{boundaries.Count}(vec2 p)\n{{\n vec3 r;\n{Common.Body(source.Code!)} return r;\n}}\n"; + edges.Add(new JsonObject { ["text"] = $"{left} = {right}", ["latex"] = Common.Latex(new Equalsf(left, right)) }); + boundaries.Add(g); + } + + var solved = Common.Try(() => (Entity)e.Solve(Y)); + var points = new JsonArray(); + for (var i = 0; i < boundaries.Count && clock.ElapsedMilliseconds < 3000; i++) + for (var j = i + 1; j < boundaries.Count && clock.ElapsedMilliseconds < 3000; j++) + { + var solutions = Common.Try(() => MathS.Equations(boundaries[i], boundaries[j]).Solve(X, Y)); + if (solutions is null) + continue; + for (var r = 0; r < solutions.RowCount; r++) + if (Common.Real(solutions[r, 0]) is { } px && Common.Real(solutions[r, 1]) is { } py) + points.Add(new JsonObject + { + ["x"] = px, ["y"] = py, + ["text"] = $"({solutions[r, 0]}, {solutions[r, 1]})", + }); + } + + return new JsonObject + { + ["ok"] = true, + ["dims"] = 2, + ["latex"] = Common.Latex(e), + ["glsl"] = glsl, + ["edges"] = edges, + ["solvedY"] = solved?.ToString() ?? "", + ["solvedYLatex"] = Common.Latex(solved), + ["points"] = points, + ["ms"] = clock.ElapsedMilliseconds, + }.ToJsonString(); + } + + private static string Line(Entity e, Stopwatch clock) + { + Entity? set; + string how; + if (e is Entity.Set) + { + set = Common.Try(() => e.Simplify()); + how = "simplified"; + } + else if (e is Statement) + { + set = Common.Try(() => (Entity)e.Solve(X)); + how = "solved for x"; + } + else + return Common.Fail("Type a comparison in x, such as x^2 < 4, or a set such as [1; 3) \\/ (2; 5]."); + if (set is null) + return Common.Fail(e is Statement + ? "AngouriMath could not solve this for x. Its inequality solver handles polynomials, not abs, sin and the like." + : "AngouriMath could not simplify this set."); + return new JsonObject + { + ["ok"] = true, + ["dims"] = 1, + ["latex"] = Common.Latex(e), + ["how"] = how, + ["set"] = set.ToString(), + ["setLatex"] = Common.Latex(set), + ["intervals"] = Common.Intervals(set), + ["ms"] = clock.ElapsedMilliseconds, + }.ToJsonString(); + } +} diff --git a/live/Demos/Representations.cs b/live/Demos/Representations.cs new file mode 100644 index 0000000000..aa99f9d273 --- /dev/null +++ b/live/Demos/Representations.cs @@ -0,0 +1,215 @@ +using System.Globalization; +using System.Text.Json.Nodes; +using AngouriMath; +using AngouriMath.Core; +using AngouriMath.Core.Budgets; +using AngouriMath.Core.Transformations; +using static AngouriMath.Entity; + +namespace AmLive; + +/// +/// The representations demo: one formula, every form AngouriMath can give it. Text, LaTeX, +/// SymPy, the simplified form, the expression tree, shader source, and the picture that suits +/// it: a plot, a heat map, a truth table, a number line or a value. And whether it equals a +/// second formula. +/// +public static class Representations +{ + private static FastExpression? plotted; + + public static string Describe(string text) + { + var e = Common.Parse(text, out var error); + if (e is null) + return Common.Fail(error); + + var vars = Common.VarsOf(e); + var o = new JsonObject + { + ["ok"] = true, + ["text"] = e.ToString(), + ["latex"] = Common.Latex(e), + ["vars"] = Common.Strings(vars.Select(v => v.Name)), + ["sympy"] = Common.Try(() => MathS.ToSympyCode(e)) ?? "", + }; + // The text again with the glyphs of MathS.Settings.UnicodeOutput, which the parser reads back. + string? unicode = null; + MathS.Settings.UnicodeOutput.As(true, () => unicode = Common.Try(() => e.ToString())); + o["unicode"] = unicode ?? ""; + + var simplified = Common.Try(() => e.Simplify()); + o["simplified"] = simplified?.ToString() ?? ""; + o["simplifiedLatex"] = Common.Latex(simplified); + + // The other rewrites: one tidying pass, products multiplied out, factors gathered, and + // the forms simplify weighs against each other, simplest first. Forms that typeset the + // same (x + -6 and x - 6) are shown once. + var forms = new JsonObject(); + foreach (var (name, form) in new (string, Func)[] + { ("normalized", () => e.InnerSimplified), ("expanded", () => e.Expand()), ("factorized", () => e.Factorize()) }) + { + var f = Common.Try(form); + forms[name] = new JsonObject { ["text"] = f?.ToString() ?? "", ["latex"] = Common.Latex(f) }; + } + var alternatives = new JsonArray(); + var seen = new HashSet(); + foreach (var a in Common.Try(() => e.Alternate(2).Take(16).ToList()) ?? new List()) + if (alternatives.Count < 6 && Common.Latex(a) is var latex && seen.Add(latex)) + alternatives.Add(new JsonObject { ["text"] = a.ToString(), ["latex"] = latex }); + forms["alternatives"] = alternatives; + o["forms"] = forms; + + var budget = 120; + o["tree"] = Common.Tree(e, ref budget); + var nodes = e.Nodes.ToList(); + o["nodes"] = nodes.Count; + // Records compare by value, so equal subtrees collapse: what a shader computes once. + o["distinct"] = nodes.Distinct().Count(); + + plotted = null; + if (Common.AsLetters(e) is var lettered && IsLogic(lettered)) + { + o["kind"] = "logic"; + var letters = Common.VarsOf(lettered); + if (letters.Count is > 0 and <= 6) + o["truth"] = TruthTable(lettered, letters); + } + else if (e is Entity.Set) + { + o["kind"] = "set"; + var set = simplified ?? e; + o["intervals"] = Common.Intervals(set); + } + else if (e is Statement && vars.Count == 1) + { + o["kind"] = "set"; + var solved = Common.Try(() => e.Solve(vars[0])); + if (solved is null) + o["note"] = $"AngouriMath could not solve this for {vars[0]}."; + else + { + o["solved"] = solved.ToString(); + o["solvedLatex"] = Common.Latex(solved); + o["intervals"] = Common.Intervals(solved); + } + } + else if (vars.Count == 0) + { + o["kind"] = "value"; + o["value"] = Common.Try(() => e.EvalNumerical().ToString()) ?? ""; + } + else if (vars.Count <= 2) + { + o["kind"] = vars.Count == 1 ? "curve" : (e is Statement ? "region" : "surface"); + var names = new Dictionary { [vars[0]] = "p.x" }; + if (vars.Count == 2) + names[vars[1]] = "p.y"; + var output = new List> { new("r", e) }; + var glsl = MathS.Shaders.Glsl(output, names); + var hlsl = MathS.Shaders.Hlsl(output, names); + var type = e is Statement ? "bool" : "float"; + if (glsl.Succeeded) + o["glsl"] = $"{type} f(vec2 p)\n{{\n {type} r;\n{Common.Body(glsl.Code!)} return r;\n}}\n"; + else + o["glslReason"] = glsl.ToString(); + if (hlsl.Succeeded) + o["hlsl"] = $"{type} f(float2 p)\n{{\n {type} r;\n{Common.Body(hlsl.Code!)} return r;\n}}\n"; + if (vars.Count == 1) + plotted = Common.TryCompile(e, vars[0]); + } + else + o["kind"] = "other"; + return o.ToJsonString(); + } + + // What one equality question may spend. Steps count work, not time, so the answer is the same + // on any machine. + private const long CompareSteps = 20_000; + + /// + /// Whether two formulas are equal, by MathS.AreEqual, which has three answers: proved by + /// rewrite rules, refuted at a point, or neither. Asked over the complex numbers and over the + /// reals; each time first with the rules that hold with no side condition, and where that + /// decides nothing, with the conditional ones as well. + /// + public static string Compare(string leftText, string rightText) + { + var left = Common.Parse(leftText, out var error); + if (left is null) + return Common.Fail(error); + var right = Common.Parse(rightText, out error); + if (right is null) + return Common.Fail(error); + + var budget = new WorkBudget { Steps = CompareSteps }; + var answers = new JsonArray(); + foreach (var domain in new[] { Domain.Complex, Domain.Real }) + { + EqualityAnswer answer; + try + { + answer = MathS.AreEqual(left, right, budget, Soundness.Sound, domain); + if (answer.Verdict == EqualityVerdict.Unknown) + answer = MathS.AreEqual(left, right, budget, Soundness.SoundUnderAssumptions, domain); + } + catch (Exception e) + { + return Common.Fail($"AngouriMath did not compare these: {e.Message}"); + } + + var o = new JsonObject + { + ["domain"] = domain == Domain.Real ? "real" : "complex", + ["verdict"] = answer.Verdict.ToString(), + ["sound"] = JsonValue.Create(answer.Justification == Soundness.Sound), + ["rules"] = Common.Strings(answer.Assumptions.Select(rule => rule.Replace('-', ' '))), + ["finished"] = JsonValue.Create(answer.Budget.Completed), + }; + // The point that refutes, and what each side is there. + if (answer.Verdict == EqualityVerdict.NotEqual && answer.Witness is { } witness) + { + Entity At(Entity side) => witness.Aggregate(side, (e, point) => e.Substitute(point.Key, point.Value)); + o["atLatex"] = string.Join(@",\quad ", witness.Select(point => $"{Common.Latex(point.Key)} = {Common.Latex(point.Value)}")); + o["leftAt"] = Approximate(At(left)); + o["rightAt"] = Approximate(At(right)); + } + answers.Add(o); + } + return new JsonObject { ["ok"] = true, ["steps"] = CompareSteps, ["answers"] = answers }.ToJsonString(); + } + + /// A closed expression's value to eight digits, for reading beside another. + private static string Approximate(Entity e) + { + if (Common.Try(() => e.EvalNumerical()) is not Number.Complex z || z.IsNaN) + return "no value"; + var c = z.ToNumerics(); + static string Digits(double d) => d.ToString("G8", CultureInfo.InvariantCulture).Replace("-", "−"); + if (c.Imaginary == 0) + return Digits(c.Real); + var sign = c.Imaginary < 0 ? "−" : "+"; + return c.Real == 0 ? $"{Digits(c.Imaginary)}i" : $"{Digits(c.Real)} {sign} {Digits(Math.Abs(c.Imaginary))}i"; + } + + /// The last described function of one variable over [from, to]. + public static double[] Sample(double from, double to, int n) => Common.Sample(plotted, from, to, n); + + internal static bool IsLogic(Entity e) => + e is Statement && e.Nodes.All(n => n is Variable or Entity.Boolean or Andf or Orf or Xorf or Notf or Impliesf); + + internal static JsonObject TruthTable(Entity e, List vars) + { + var table = MathS.Boolean.BuildTruthTable(e, vars.ToArray()); + var rows = new JsonArray(); + if (table is not null) + for (var i = 0; i < table.RowCount; i++) + { + var row = new JsonArray(); + for (var j = 0; j < table.ColumnCount; j++) + row.Add(JsonValue.Create(table[i, j] is Entity.Boolean { Value: true })); + rows.Add(row); + } + return new JsonObject { ["vars"] = Common.Strings(vars.Select(v => v.Name)), ["rows"] = rows }; + } +} diff --git a/live/Demos/Senses.cs b/live/Demos/Senses.cs new file mode 100644 index 0000000000..0cfc0becf0 --- /dev/null +++ b/live/Demos/Senses.cs @@ -0,0 +1,561 @@ +using System.Text.Json.Nodes; +using AngouriMath; +using static AngouriMath.Entity; + +namespace AmLive; + +/// +/// The senses demo: a formula over the named states of real signals, read the way the LogicState +/// catalogue reads them (Rafael-SOWNet/UnitsNet, spike/logic-state). A sense says which condition +/// a stored 1 means, and its opposite reads the same bit the other way round, so Closed from one +/// device and Open from another are one letter, once negated. Facts about the plant that logic +/// does not know, such as a full tank not being empty, are invariants: a row that breaks one cannot +/// occur, so the minimal form may treat it as a don't-care, and seeing one means a signal is wrong. +/// +public static class Senses +{ + /// A sense and its opposite: the same bit read the other way round. + private sealed record Pair(string True, string False, string Source); + + // Each pair of the catalogue, the sense in which 1 means what its name says first. The sources + // are the catalogue's; it names none for Valid and Fault. + private static readonly Pair[] Catalogue = + [ + new("Active", "Inactive", "BACnet; KNX DPT 1.011"), + new("On", "Off", "KNX DPT 1.001"), + new("Enabled", "Disabled", "KNX DPT 1.003"), + new("Present", "Absent", "presence detection"), + new("Occupied", "Unoccupied", "KNX DPT 1.018"), + new("Alarm", "NoAlarm", "KNX DPT 1.005"), + new("High", "Low", "KNX DPT 1.006; Low is active-low signalling"), + new("Open", "Closed", "KNX DPT 1.019 (1 = open) and 1.009 (1 = close)"), + new("Valid", "Invalid", ""), + new("Fault", "NoFault", ""), + new("Pressed", "Depressed", "a normally-open and a normally-closed button"), + new("Near", "Far", "proximity switch"), + new("Running", "Stopped", "OPC UA TwoStateDiscreteType"), + new("Safe", "Unsafe", "OPC UA TwoStateDiscreteType"), + new("Connected", "Disconnected", "the link, not what it measures"), + new("Succeeded", "Failed", "the outcome of a finished operation"), + new("Acknowledged", "Unacknowledged", "ANSI/ISA-18.2; KNX DPT 1.016"), + new("Local", "Remote", "IEC 61850 Loc"), + new("InService", "OutOfService", "BACnet Out_Of_Service"), + new("Set", "Reset", "IEC 61131-3 SR/RS; KNX DPT 1.015"), + new("Up", "Down", "KNX DPT 1.008; neither side is naturally true"), + new("Increase", "Decrease", "KNX DPT 1.007"), + new("Heating", "Cooling", "KNX DPT 1.100"), + new("Shelved", "Unshelved", "ANSI/ISA-18.2; OPC UA Part 9"), + new("Suppressed", "Unsuppressed", "ANSI/ISA-18.2; OPC UA Part 9"), + new("Latched", "Unlatched", "ANSI/ISA-18.2; OPC UA Part 9"), + new("Confirmed", "Unconfirmed", "OPC UA Part 9"), + new("Silenced", "Unsilenced", "OPC UA Part 9"), + new("Blocked", "Unblocked", "PackML"), + new("Starved", "NotStarved", "PackML"), + new("OutOfSpecification", "InSpecification", "NAMUR NE 107"), + new("MaintenanceRequired", "NoMaintenanceRequired", "NAMUR NE 107"), + new("Inverted", "NotInverted", "KNX DPT 1.012; BACnet Polarity"), + new("Calculated", "Fixed", "KNX DPT 1.014"), + new("Full", "NotFull", "point-level detector; no naming standard"), + new("Empty", "NotEmpty", "point-level detector; no naming standard"), + ]; + + /// + /// Senses that cannot both hold on one channel, kept as separate pairs because both can be + /// false. Each becomes an invariant wherever a formula uses both on the same channel. + /// + private static readonly (string A, string B, string Why)[] Exclusive = + [ + ("Full", "Empty", "A vessel is never full and empty at once. The catalogue keeps them as two pairs because a part-filled one is neither."), + ]; + + /// A word of the formula: a sense of a pair on a channel, or a letter of its own. + private readonly record struct Reading(Pair? Pair, bool Negated, string Channel); + + /// Reads Closed_door as the Open/Closed pair, negated, on the channel door. Case does not matter. + private static Reading Read(string word) + { + var cut = word.IndexOf('_'); + var (name, channel) = cut < 0 ? (word, "") : (word[..cut], word[(cut + 1)..]); + foreach (var pair in Catalogue) + if (string.Equals(name, pair.True, StringComparison.OrdinalIgnoreCase)) + return new(pair, false, channel); + else if (string.Equals(name, pair.False, StringComparison.OrdinalIgnoreCase)) + return new(pair, true, channel); + return new(null, false, ""); + } + + private static string Named(string sense, string channel) => channel.Length == 0 ? sense : $"{sense}_{channel}"; + + /// The formula in letters, one per channel and named after its true sense; an opposite sense is its negation. + private static Entity InLetters(Entity e) => e.Replace(node => + node is Variable v && Read(v.Name) is { Pair: { } pair } r + ? r.Negated ? !MathS.Var(Named(pair.True, r.Channel)) : MathS.Var(Named(pair.True, r.Channel)) + : node); + + /// The formula in senses: each negated letter of a pair written as the opposite sense, which needs no inverter. + private static Entity InSenses(Entity e) => e.Replace(node => + node is Notf { Argument: Variable v } && Read(v.Name) is { Pair: { } pair, Negated: false } r + ? MathS.Var(Named(pair.False, r.Channel)) + : node); + + private static bool IsFormula(Entity e) => e is Variable || Representations.IsLogic(e); + + /// The catalogue itself, for the page to show as a reference. + public static string Reference() => new JsonObject + { + ["pairs"] = new JsonArray(Catalogue.Select(p => (JsonNode)new JsonObject + { + ["true"] = p.True, + ["false"] = p.False, + ["source"] = p.Source, + }).ToArray()), + ["exclusive"] = new JsonArray(Exclusive.Select(x => (JsonNode)new JsonObject + { + ["a"] = x.A, + ["b"] = x.B, + ["notB"] = Catalogue.First(p => p.True == x.B).False, + ["why"] = x.Why, + }).ToArray()), + }.ToJsonString(); + + /// A line of the formula field: Name = formula, or a formula alone (no name). + private static (string? Name, string Body) Definition(string line) + { + var end = 0; + while (end < line.Length && (char.IsLetterOrDigit(line[end]) || line[end] == '_')) + end++; + var at = end; + while (at < line.Length && line[at] == ' ') + at++; + if (at < line.Length && line[at] == ':') + at++; + return end > 0 && char.IsLetter(line[0]) && at < line.Length && line[at] == '=' && (at + 1 == line.Length || line[at + 1] != '=') + ? (line[..end], line[(at + 1)..]) + : (null, line); + } + + private static bool IsComparison(Entity e) => e is Greaterf or Lessf or GreaterOrEqualf or LessOrEqualf; + + private static (Entity Left, Entity Right) Sides(Entity comparison) => comparison switch + { + Greaterf c => (c.Left, c.Right), + GreaterOrEqualf c => (c.Left, c.Right), + Lessf c => (c.Left, c.Right), + LessOrEqualf c => (c.Left, c.Right), + _ => throw new ArgumentException("Not a comparison.", nameof(comparison)), + }; + + /// The comparison that holds exactly where this one does not, for real numbers. + private static Entity Negate(Entity comparison) => comparison switch + { + Greaterf c => new LessOrEqualf(c.Left, c.Right), + GreaterOrEqualf c => new Lessf(c.Left, c.Right), + Lessf c => new GreaterOrEqualf(c.Left, c.Right), + LessOrEqualf c => new Greaterf(c.Left, c.Right), + _ => !comparison, + }; + + private static string Label(Entity comparison) => comparison.ToString().Replace("<=", "≤").Replace(">=", "≥"); + + private static string LetterOf(string word) => Read(word) is { Pair: { } pair } r ? Named(pair.True, r.Channel) : word; + + /// An invariant that rules out one product of letters, said as an implication where it has that shape. + private static Entity RulingOut(Entity never) => never switch + { + Andf { Left: Variable a, Right: Notf { Argument: Variable b } } => a.Implies(b), + Andf { Left: Notf { Argument: Variable b }, Right: Variable a } => a.Implies(b), + Notf n => n.Argument, + _ => !never, + }; + + private sealed record Rule(Entity Formula, string Latex, string Why, bool Builtin); + + /// + /// Each line is an output, Name = formula, or a condition, Name = comparison of real numbers. A + /// comparison inside a formula is a condition of its own. Outputs may use the ones above them. + /// + public static string Analyze(string text, string always) + { + var lines = text.Split([';', '\n'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + if (lines.Length == 0) + return Common.Fail("Type a formula."); + var parts = new List<(string? Name, Entity Body)>(); + foreach (var line in lines) + { + var (name, body) = Definition(line); + var parsed = Common.Parse(body, out var error); + if (parsed is null) + return Common.Fail(name is null ? error : $"{name}: {error}"); + parts.Add((name, parsed)); + } + if (parts.Count > 1 && parts.Any(p => p.Name is null)) + return Common.Fail("Name each output when there are several, one per line, as in On_pump = On_request and NotEmpty_tank."); + if (parts.Count > 8) + return Common.Fail("Use at most eight lines."); + + // Comparisons become letters. A named one takes its name; one inside a formula gets a letter + // that is shown as the comparison. A comparison and its negation share the letter. + var conditions = new List<(Variable Letter, Entity Comparison, string? Name)>(); + var compared = new Dictionary(); + var inline = new Dictionary(); + foreach (var (name, body) in parts) + { + if (name is null || !IsComparison(body)) + continue; + var letter = MathS.Var(LetterOf(name)); + var where = Read(name) is { Pair: not null, Negated: true } ? Negate(body) : body; + if (conditions.Any(c => c.Letter == letter) || compared.ContainsKey(where.ToString())) + return Common.Fail($"{name} repeats a condition already defined."); + conditions.Add((letter, where, name)); + compared[where.ToString()] = letter; + compared[Negate(where).ToString()] = !letter; + } + Entity Lettered(Entity e) => Common.AsLetters(e.Replace(node => + { + if (!IsComparison(node)) + return node; + if (!node.Vars.Any()) + return Common.Try(() => node.Evaled) is Entity.Boolean value ? value : node; + if (compared.TryGetValue(node.ToString(), out var known)) + return known; + var letter = MathS.Var($"cmp_{inline.Count + 1}"); + inline[letter.Name] = node; + conditions.Add((letter, node, null)); + compared[node.ToString()] = letter; + compared[Negate(node).ToString()] = !letter; + return letter; + })); + // Shown: each comparison letter as its comparison, a negated one turned round, and senses. + Entity Unlettered(Entity e) => e.Replace(node => node is Variable v && inline.TryGetValue(v.Name, out var c) ? c : node); + Entity Display(Entity e) => InSenses(Unlettered(e).Replace(node => node is Notf { Argument: var a } && IsComparison(a) ? Negate(a) : node)); + + var outputLetters = parts.Where(p => p.Name is not null && !IsComparison(p.Body)).Select(p => LetterOf(p.Name!)).ToList(); + if (outputLetters.Distinct().Count() != outputLetters.Count) + return Common.Fail("Two outputs name one channel; define each once."); + var outputs = new List<(string? Name, Entity Written, Entity Formula)>(); + var words = new List(); + var defined = new Dictionary(); + foreach (var (name, body) in parts) + { + if (name is not null && IsComparison(body)) + continue; + var logic = Lettered(body); + if (!IsFormula(logic)) + return Common.Fail($"{name ?? "The formula"} is not a formula in senses: use senses such as Open_door, comparisons such as T > 100, and and, or, xor, implies and not."); + words.Add(logic); + var formula = InLetters(logic).Replace(node => node is Variable v && defined.TryGetValue(v.Name, out var f) ? f : node); + if (formula.Vars.FirstOrDefault(v => outputLetters.Contains(v.Name)) is { } early) + return Common.Fail($"{early.Name} is an output used above its own line; define an output before using it."); + if (name is not null) + defined[LetterOf(name)] = Read(name) is { Pair: not null, Negated: true } ? !formula : formula; + outputs.Add((name, body, formula)); + } + if (outputs.Count == 0) + return Common.Fail("Add an output that uses the conditions, as in On_alarm = On_kettle and above_boilingpoint."); + + // An invariant over inputs is a fact about the plant: it decides which rows can occur. One + // that mentions an output is a check on the design instead, true or not in those rows, and + // the outputs in it are replaced by their formulas. + var rules = new List(); + var checks = new List<(string Latex, Entity Formula)>(); + foreach (var part in always.Split([';', '\n'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + { + var parsed = Common.Parse(part, out var error); + if (parsed is null) + return Common.Fail($"In the invariants: {error}"); + var logic = Lettered(parsed); + if (!IsFormula(logic)) + return Common.Fail($"The invariant “{part}” is not a formula in senses."); + words.Add(logic); + var formula = InLetters(logic); + if (formula.Vars.Any(v => outputLetters.Contains(v.Name))) + checks.Add((Common.Latex(parsed), formula.Replace(node => node is Variable v && defined.TryGetValue(v.Name, out var f) ? f : node))); + else + rules.Add(new(formula, Common.Latex(parsed), "", false)); + } + var reals = conditions.SelectMany(c => c.Comparison.Vars).Select(v => v.Name).ToHashSet(); + var everything = outputs.Select(o => o.Formula).Concat(rules.Select(r => r.Formula)).Concat(checks.Select(c => c.Formula)).ToList(); + if (everything.SelectMany(e => e.Vars).FirstOrDefault(v => reals.Contains(v.Name)) is { } clash) + return Common.Fail($"{clash.Name} is a number in a comparison and a true-or-false letter elsewhere."); + + var letters = everything.SelectMany(e => e.Vars).Select(v => v.Name).ToHashSet(); + foreach (var (a, b, why) in Exclusive) + { + var notB = Catalogue.First(p => p.True == b).False; + foreach (var channel in letters.Select(Read).Where(r => r.Pair?.True == a).Select(r => r.Channel).Distinct().Order(StringComparer.Ordinal)) + if (letters.Contains(Named(b, channel))) + { + var rule = MathS.FromString($"{Named(a, channel)} implies {Named(notB, channel)}"); + rules.Add(new(InLetters(rule), Common.Latex(rule), why, true)); + } + } + + // What AngouriMath knows about the comparisons: those on one real number constrain each other. + var notes = new List(); + foreach (var group in conditions.Where(c => letters.Contains(c.Letter.Name)) + .GroupBy(c => string.Join(", ", c.Comparison.Vars.Select(v => v.Name).Order(StringComparer.Ordinal)))) + { + var members = group.ToList(); + var x = members[0].Comparison.Vars.ToList() is [var only] ? only : null; + if (x is null && group.Key.Length > 0) + { + notes.Add($"Comparisons on {group.Key} together are taken as independent: AngouriMath finds where one number crosses a value, not where several do."); + continue; + } + if (Feasible(members.Select(m => m.Comparison).ToList(), x, out var turns) is not { } feasible) + { + notes.Add($"AngouriMath could not list where the comparisons on {group.Key} turn, so they are taken as independent."); + continue; + } + var never = Enumerable.Range(0, 1 << members.Count).Where(i => !feasible.Contains(i)).ToList(); + var why = x is null ? "A comparison of numbers alone is true or false once and for all." + : $"For every real {x}: AngouriMath solved where the comparisons on {x} turn, at {string.Join(", ", turns)}, and tested a value in each interval between. If they come from separate switches, one that breaks this is broken."; + foreach (var term in Logic.MinimalCover(never, members.Count)) + { + var rule = RulingOut(Logic.SumOfProducts([term], members.Select(m => m.Letter).ToList())); + rules.Add(new(rule, Common.Latex(Display(rule)), why, true)); + } + } + + var vars = outputs.SelectMany(o => o.Formula.Vars).Distinct() + .OrderBy(v => inline.TryGetValue(v.Name, out var c) ? Label(c) : v.Name, StringComparer.Ordinal).ToList(); + if (vars.Count == 0 || vars.Count > 6) + return Common.Fail("Use between one and six inputs, counting each comparison as one."); + Entity holds = rules.Count == 0 ? true : rules.Select(r => r.Formula).Aggregate((x, y) => x & y); + var all = vars.Concat(Common.VarsOf(holds).Where(v => !vars.Contains(v))).ToList(); + if (all.Count > 10) + return Common.Fail("Use at most ten inputs across the outputs and the invariants."); + + // A row of the outputs' inputs can occur when some value of the invariants' other letters satisfies them. + var n = vars.Count; + var possible = new bool[1 << n]; + if (rules.Count == 0) + Array.Fill(possible, true); + else if (TrueRows(holds, all) is { } holding) + foreach (var row in holding) + possible[row >> (all.Count - n)] = true; + else + return Common.Fail("AngouriMath could not build the truth table of the invariants."); + if (!possible.Contains(true)) + return Common.Fail("The invariants contradict each other: no value of the signals satisfies them all."); + var dontCares = Enumerable.Range(0, 1 << n).Where(i => !possible[i]).ToList(); + + var columns = new List>(); + var described = new JsonArray(); + foreach (var (name, written, formula) in outputs) + { + var rows = (TrueRows(formula, vars) ?? []).ToHashSet(); + columns.Add(rows); + var cover = Logic.MinimalCover(rows.Where(i => possible[i]).Order().ToList(), n, dontCares); + var minimal = Logic.SumOfProducts(cover, vars); + var simplified = Common.Try(() => formula.Simplify()); + described.Add(new JsonObject + { + ["name"] = name, + ["nameLatex"] = name is null ? null : Common.Latex(MathS.Var(name)), + ["latex"] = Common.Latex(written), + ["lettersLatex"] = Common.Latex(Unlettered(formula)), + ["simplifiedLatex"] = Common.Latex(simplified is null ? null : Display(simplified)), + ["simplifiedEquivalent"] = simplified is not null && NeverTrue(formula.Xor(simplified)), + ["sop"] = Display(minimal).ToString(), + ["sopLatex"] = Common.Latex(Display(minimal)), + ["sopEquivalent"] = NeverTrue(formula.Xor(minimal) & holds), + ["groups"] = new JsonArray(cover.Select(c => (JsonNode)new JsonObject { ["mask"] = c.Mask, ["value"] = c.Value }).ToArray()), + }); + } + + string Shown(Variable v) => inline.TryGetValue(v.Name, out var c) ? Label(c) : v.Name; + string Opposite(Variable v) => inline.TryGetValue(v.Name, out var c) ? Label(Negate(c)) + : Read(v.Name) is { Pair: { } pair } r ? Named(pair.False, r.Channel) : $"¬{v.Name}"; + var o = new JsonObject + { + ["ok"] = true, + ["inputs"] = new JsonArray(vars.Select(v => (JsonNode)new JsonObject { ["label"] = Shown(v), ["opposite"] = Opposite(v) }).ToArray()), + ["outputs"] = described, + ["truth"] = new JsonObject + { + ["vars"] = new JsonArray(vars.Select(v => (JsonNode)JsonValue.Create(Shown(v))).ToArray()), + ["outputs"] = new JsonArray(outputs.Select(p => (JsonNode)JsonValue.Create(p.Name ?? "value")).ToArray()), + ["rows"] = new JsonArray(Enumerable.Range(0, 1 << n).Select(i => (JsonNode)new JsonArray( + Enumerable.Range(0, n).Select(j => (JsonNode)JsonValue.Create(((i >> (n - 1 - j)) & 1) == 1)) + .Concat(columns.Select(c => (JsonNode)JsonValue.Create(c.Contains(i)))).ToArray())).ToArray()), + ["possible"] = new JsonArray(possible.Select(p => (JsonNode)JsonValue.Create(p)).ToArray()), + }, + ["dontCares"] = new JsonArray(dontCares.Select(i => (JsonNode)JsonValue.Create(i)).ToArray()), + }; + + var outputWords = parts.Where(p => p.Name is not null && !IsComparison(p.Body)).Select(p => p.Name!); + var named = conditions.Where(c => c.Name is not null).ToDictionary(c => c.Letter.Name, c => c.Comparison); + o["senses"] = new JsonArray(outputWords.Concat(words.SelectMany(e => e.Vars).Select(v => v.Name).Where(w => !inline.ContainsKey(w))) + .Distinct() + .Select(word => (Word: word, Reading: Read(word), Letter: LetterOf(word))) + .OrderBy(w => w.Letter, StringComparer.Ordinal).ThenBy(w => w.Word, StringComparer.Ordinal) + .Select(w => (JsonNode)new JsonObject + { + ["word"] = w.Word, + ["letter"] = w.Letter, + ["negated"] = w.Reading.Negated, + ["pair"] = w.Reading.Pair is { } p ? $"{p.True} / {p.False}" : null, + ["source"] = w.Reading.Pair?.Source, + ["output"] = outputLetters.Contains(w.Letter), + ["condition"] = named.TryGetValue(w.Letter, out var c) ? Label(c) : null, + }).ToArray()); + o["conditions"] = new JsonArray(conditions.Where(c => letters.Contains(c.Letter.Name)).Select(c => (JsonNode)new JsonObject + { + ["name"] = c.Name, + ["latex"] = Common.Latex(c.Comparison), + }).ToArray()); + o["notes"] = new JsonArray(notes.Select(t => (JsonNode)JsonValue.Create(t)).ToArray()); + o["rules"] = new JsonArray(rules.Select(r => (JsonNode)new JsonObject + { + ["latex"] = r.Latex, + ["builtin"] = r.Builtin, + ["why"] = r.Why, + }).ToArray()); + + // The invariants fail only when a signal is wrong, so their failure is an alarm. + if (rules.Count > 0) + { + var ruleVars = Common.VarsOf(holds); + var fault = ruleVars.Count <= 6 && TrueRows(!holds, ruleVars) is { } broken + ? Logic.SumOfProducts(Logic.MinimalCover(broken, ruleVars.Count), ruleVars) + : Common.Try(() => (!holds).Simplify()); + o["faultLatex"] = Common.Latex(fault is null ? null : Display(fault)); + // Each term of the alarm is a condition of its own, so the page can list them. + o["faultTerms"] = new JsonArray((fault is null ? [] : Disjuncts(Display(fault))) + .Select(t => (JsonNode)JsonValue.Create(Common.Latex(t))).ToArray()); + o["faultEquivalent"] = fault is not null && NeverTrue(fault.Xor(!holds)); + o["faultNever"] = fault is Entity.Boolean { Value: false }; + } + + // A check holds when no row that can occur breaks it: AngouriMath's truth table of the + // invariants and the check's negation has no true row. Where it fails, the rows that break + // it are described by their minimal form, with the rows that cannot occur as don't-cares. + o["checks"] = new JsonArray(checks.Select(check => + { + var space = Common.VarsOf(check.Formula & holds); + var broken = TrueRows(holds & !check.Formula, space) ?? []; + var result = new JsonObject { ["latex"] = check.Latex, ["holds"] = broken.Count == 0 }; + if (broken.Count == 0) + return (JsonNode)result; + var occur = TrueRows(holds, space) ?? []; + result["broken"] = broken.Count; + result["occur"] = occur.Count; + var when = space.Count <= 8 + ? Logic.SumOfProducts(Logic.MinimalCover(broken, space.Count, Enumerable.Range(0, 1 << space.Count).Except(occur).ToList()), space) + : Common.Try(() => (holds & !check.Formula).Simplify()); + result["whenTerms"] = new JsonArray((when is null ? [] : Disjuncts(Display(when))) + .Select(t => (JsonNode)JsonValue.Create(Common.Latex(t))).ToArray()); + var bits = broken[0]; + result["example"] = string.Join(", ", Common.VarsOf(check.Formula).Select(v => + ((bits >> (space.Count - 1 - space.IndexOf(v))) & 1) == 1 ? Shown(v) : Opposite(v))); + return result; + }).ToArray()); + return o.ToJsonString(); + } + + /// + /// The combinations of the comparisons that some real satisfies, as indices + /// (bit i from the left is comparison i), and the points where they turn. Each side is taken to + /// be continuous, so a comparison turns only where its sides are equal: AngouriMath solves for + /// those points, and each point and one value in every interval between them are tested. Null + /// when a solution is not a list of numbers. + /// + private static HashSet? Feasible(List comparisons, Variable? x, out List turns) + { + turns = []; + var points = new List<(Entity Exact, double Value)>(); + if (x is not null) + foreach (var comparison in comparisons) + { + var (left, right) = Sides(comparison); + if (Common.Try(() => MathS.SolveEquation(left - right, x)) is not { } set || Listed(set) is not { } roots) + return null; + foreach (var root in roots) + if (Common.Real(root) is { } value && !points.Any(p => Math.Abs(p.Value - value) <= 1e-12 * Math.Max(1, Math.Abs(value)))) + points.Add((root, value)); + } + points.Sort((a, b) => a.Value.CompareTo(b.Value)); + turns = points.Select(p => p.Exact).ToList(); + var samples = new List(); + if (points.Count == 0) + samples.Add(0); + else + { + samples.Add(points[0].Value - 1); + for (var i = 0; i < points.Count; i++) + { + samples.Add(points[i].Exact); + samples.Add(i + 1 < points.Count ? (points[i].Value + points[i + 1].Value) / 2 : points[i].Value + 1); + } + } + var feasible = new HashSet(); + foreach (var sample in samples) + { + var index = 0; + foreach (var comparison in comparisons) + { + var at = x is null ? comparison : comparison.Substitute(x, sample); + if (Common.Try(() => at.Simplify().Evaled) is not Entity.Boolean value) + { + index = -1; + break; + } + index = index * 2 + (value.Value ? 1 : 0); + } + if (index >= 0) + feasible.Add(index); + } + return feasible; + } + + /// The numbers in a solution set, or null when it is not a plain list of them. + private static List? Listed(Entity set) => set switch + { + Entity.Set.FiniteSet finite when finite.All(e => !e.Vars.Any()) => finite.ToList(), + Entity.Set.Unionf u when Listed(u.Left) is { } l && Listed(u.Right) is { } r => l.Concat(r).ToList(), + _ => null, + }; + + /// Whether the formula is false in every row of AngouriMath's truth table over its own letters. + private static bool NeverTrue(Entity e) => TrueRows(e, Common.VarsOf(e)) is []; + + private static IEnumerable Disjuncts(Entity e) => + e is Orf or ? Disjuncts(or.Left).Concat(Disjuncts(or.Right)) : [e]; + + /// + /// The rows over where the formula is true, as indices. AngouriMath's + /// truth table is over exactly the formula's own letters, so the others are free. + /// + private static List? TrueRows(Entity e, List vars) + { + var own = vars.Where(e.Vars.ToHashSet().Contains).ToList(); + var holds = new HashSet(); + if (own.Count == 0) + { + if (Common.Try(() => e.Evaled) is not Entity.Boolean value) + return null; + if (value.Value) + holds.Add(0); + } + else + { + var table = Common.Try(() => MathS.Boolean.BuildTruthTable(e, own.ToArray())); + if (table is null) + return null; + for (var i = 0; i < table.RowCount; i++) + if (table[i, own.Count] is Entity.Boolean { Value: true }) + { + var index = 0; + for (var j = 0; j < own.Count; j++) + index = index * 2 + (table[i, j] is Entity.Boolean { Value: true } ? 1 : 0); + holds.Add(index); + } + } + // Each row over all the letters, read at the formula's own. + var positions = own.Select(v => vars.Count - 1 - vars.IndexOf(v)).ToList(); + return Enumerable.Range(0, 1 << vars.Count) + .Where(row => holds.Contains(positions.Aggregate(0, (index, bit) => index * 2 + ((row >> bit) & 1)))) + .ToList(); + } +} diff --git a/live/Demos/Shapes.cs b/live/Demos/Shapes.cs new file mode 100644 index 0000000000..c2ffbebc97 --- /dev/null +++ b/live/Demos/Shapes.cs @@ -0,0 +1,74 @@ +using System.Diagnostics; +using System.Text.Json.Nodes; +using AngouriMath; +using static AngouriMath.Entity; + +namespace AmLive; + +/// +/// The shapes demo: a surface given as f(x, y, z) = 0. AngouriMath differentiates it twice, and +/// the page ray-marches it with the exact gradient (so any implicit surface can be marched, not +/// only distance fields) and colours it by curvature from the exact Hessian. +/// +public static class Shapes +{ + private static readonly Variable[] Xyz = { "x", "y", "z" }; + + private static readonly Dictionary Names = new() + { + ["x"] = "p.x", ["y"] = "p.y", ["z"] = "p.z", + }; + + public static string Generate(string text) + { + var clock = Stopwatch.StartNew(); + var f = Common.Parse(text, out var error); + if (f is null) + return Common.Fail(error); + var stray = f.Vars.Where(v => !Xyz.Contains(v)).Select(v => v.Name).ToList(); + if (stray.Count > 0) + return Common.Fail($"Use only x, y and z. This formula also has {string.Join(", ", stray)}."); + + var g = Xyz.Select(v => Common.Unconditional(f.Differentiate(v))).ToArray(); + Entity H(int i, int j) => Common.Unconditional(g[i].Differentiate(Xyz[j])); + var value = new List> { new("v", f) }; + var gradient = new List> + { + new("r.x", f), new("r.y", g[0]), new("r.z", g[1]), new("r.w", g[2]), + }; + var hessian = new List> + { + new("Hd.x", H(0, 0)), new("Hd.y", H(1, 1)), new("Hd.z", H(2, 2)), + new("Ho.x", H(0, 1)), new("Ho.y", H(0, 2)), new("Ho.z", H(1, 2)), + }; + + var glsl = new[] { value, gradient, hessian }.Select(o => MathS.Shaders.Glsl(o, Names)).ToArray(); + var hlsl = new[] { value, gradient, hessian }.Select(o => MathS.Shaders.Hlsl(o, Names)).ToArray(); + var declined = glsl.Concat(hlsl).FirstOrDefault(s => !s.Succeeded); + if (declined is not null) + { + var reason = declined.ToString(); + if (f.Nodes.Any(n => n is Maxf or Minf)) + reason += " AngouriMath cannot differentiate max or min; a smooth version works, such as log(e^(8 a) + e^(8 b)) / 8 for max(a, b)."; + return Common.Fail(reason); + } + + var glslSource = + $"float field(vec3 p)\n{{\n float v;\n{Common.Body(glsl[0].Code!)} return v;\n}}\n\n" + + $"vec4 fieldGrad(vec3 p)\n{{\n vec4 r;\n{Common.Body(glsl[1].Code!)} return r;\n}}\n\n" + + $"void fieldHess(vec3 p, out vec3 Hd, out vec3 Ho)\n{{\n{Common.Body(glsl[2].Code!)}}}\n"; + var hlslSource = + $"float field(float3 p)\n{{\n float v;\n{Common.Body(hlsl[0].Code!)} return v;\n}}\n\n" + + $"float4 fieldGrad(float3 p)\n{{\n float4 r;\n{Common.Body(hlsl[1].Code!)} return r;\n}}\n\n" + + $"void fieldHess(float3 p, out float3 Hd, out float3 Ho)\n{{\n{Common.Body(hlsl[2].Code!)}}}\n"; + return new JsonObject + { + ["ok"] = true, + ["glsl"] = glslSource, + ["hlsl"] = hlslSource, + ["latex"] = Common.Latex(f), + ["gradient"] = Common.Strings(g.Select(d => d.ToString())), + ["ms"] = clock.ElapsedMilliseconds, + }.ToJsonString(); + } +} diff --git a/live/Demos/Waves.cs b/live/Demos/Waves.cs new file mode 100644 index 0000000000..f677b4e140 --- /dev/null +++ b/live/Demos/Waves.cs @@ -0,0 +1,94 @@ +using System.Text.Json.Nodes; +using AngouriMath; +using AngouriMath.Core; +using static AngouriMath.Entity; + +namespace AmLive; + +/// +/// The waves demo: read a formula for a water wave's angular frequency, check its units inside +/// the wave's phase, differentiate the surface, and print it as GLSL (which the page runs) and +/// HLSL (for Unity). +/// +public static class Waves +{ + private static readonly Dimension L = Dimension.Length, T = Dimension.Time; + + // Amplitude, wavenumber, water depth, gravity, the unit direction of travel, the surface + // point and time. + private static readonly Dictionary Dims = new() + { + ["A"] = L, ["k"] = Dimension.Dimensionless / L, ["h"] = L, ["g"] = L / T.Pow(2), + ["dx"] = Dimension.Dimensionless, ["dz"] = Dimension.Dimensionless, + ["px"] = L, ["pz"] = L, ["t"] = T, + }; + + private static readonly Dictionary Names = new() + { + ["px"] = "p.x", ["pz"] = "p.y", ["dx"] = "dir.x", ["dz"] = "dir.y", ["g"] = "WAVE_G", + }; + + // The last accepted frequency with g = 9.81, for the page's speed readout and for keeping + // each wave's phase continuous when the depth or the formula changes. + private static FastExpression? omegaOfKh; + + public static string Generate(string omegaText) + { + var omega = Common.Parse(omegaText, out var error); + if (omega is null) + return new JsonObject { ["ok"] = false, ["omega"] = error, ["phase"] = "" }.ToJsonString(); + + Entity A = "A", k = "k", g = "g", dx = "dx", dz = "dz", px = "px", pz = "pz", t = "t"; + var omegaCheck = MathS.Dimensions.Of(omega, Dims); + // omega on its own may be any quantity; inside the phase it has to be a frequency. + var phase = k * (dx * px + dz * pz) - omega * t; + var phaseCheck = MathS.Dimensions.Of(phase, Dims); + var result = new JsonObject { ["omega"] = omegaCheck.ToString(), ["phase"] = phaseCheck.ToString() }; + if (!phaseCheck.IsConsistent || !phaseCheck.Dimension!.IsDimensionless) + { + result["ok"] = false; + result["kind"] = phaseCheck.Status.ToString(); + return result.ToJsonString(); + } + + var height = A * MathS.Sin(phase); + var outputs = new List> + { + new("r.x", height), + new("r.y", Common.Unconditional(height.Differentiate("px"))), + new("r.z", Common.Unconditional(height.Differentiate("pz"))), + }; + var glsl = MathS.Shaders.Glsl(outputs, Names); + var hlsl = MathS.Shaders.Hlsl(outputs, Names); + if (!glsl.Succeeded || !hlsl.Succeeded) + { + result["ok"] = false; + result["kind"] = "Declined"; + result["reason"] = (glsl.Succeeded ? hlsl : glsl).ToString(); + return result.ToJsonString(); + } + + // A consistent formula may still use A or t, which the readout does not supply. + omegaOfKh = Common.TryCompile(omega.Substitute(g, 9.81), "k", "h"); + result["ok"] = true; + result["glsl"] = $"vec3 waveHeightSlope(vec2 p, float t, float A, float k, float h, vec2 dir)\n{{\n vec3 r;\n{Common.Body(glsl.Code!)} return r;\n}}\n"; + result["hlsl"] = $"float3 waveHeightSlope(float2 p, float t, float A, float k, float h, float2 dir)\n{{\n float3 r;\n{Common.Body(hlsl.Code!)} return r;\n}}\n"; + return result.ToJsonString(); + } + + /// The accepted frequency at each wavenumber for depth h, or NaN where it has none. + public static double[] Omegas(double[] ks, double h) + { + var result = new double[ks.Length]; + for (var i = 0; i < ks.Length; i++) + { + var w = omegaOfKh?.Call(ks[i], h); + result[i] = w is { } c && c.Imaginary == 0 ? c.Real : double.NaN; + } + return result; + } + + public static string[] Groups() => + MathS.Dimensions.DimensionlessGroups(new Variable[] { "g", "k", "A", "h", "t" }, Dims) + .Select(group => group.ToString()).ToArray(); +} diff --git a/live/Program.cs b/live/Program.cs new file mode 100644 index 0000000000..57e09a8e98 --- /dev/null +++ b/live/Program.cs @@ -0,0 +1,78 @@ +using System.Runtime.InteropServices.JavaScript; + +[assembly: System.Runtime.Versioning.SupportedOSPlatform("browser")] + +// The page's worker drives everything through the exports below; each returns JSON or numbers. +Console.WriteLine("AngouriMath is running in WebAssembly."); + +namespace AmLive +{ + public static partial class WavesJs + { + [JSExport] internal static string Generate(string omega) => Waves.Generate(omega); + [JSExport] internal static double[] Omegas(double[] k, double h) => Waves.Omegas(k, h); + [JSExport] internal static string[] Groups() => Waves.Groups(); + } + + public static partial class RepresentationsJs + { + [JSExport] internal static string Describe(string text) => Representations.Describe(text); + [JSExport] internal static double[] Sample(double from, double to, int n) => Representations.Sample(from, to, n); + [JSExport] internal static string Compare(string left, string right) => Representations.Compare(left, right); + } + + public static partial class ShapesJs + { + [JSExport] internal static string Generate(string text) => Shapes.Generate(text); + } + + public static partial class CalculusJs + { + [JSExport] internal static string Analyze(string text) => Calculus.Analyze(text); + [JSExport] internal static string Taylor(string text, double a) => Calculus.Taylor(text, a); + [JSExport] internal static double[] Sample(double from, double to, int n, int order) => Calculus.Sample(from, to, n, order); + [JSExport] internal static string Area(double a, double b) => Calculus.Area(a, b); + [JSExport] internal static string Limits(string text) => Calculus.Limits(text); + [JSExport] internal static string LimitAt(string text, string at) => Calculus.LimitAt(text, at); + } + + public static partial class LogicJs + { + [JSExport] internal static string Analyze(string text) => Logic.Analyze(text); + [JSExport] internal static string Venn(string text) => Logic.Venn(text); + [JSExport] internal static string Senses(string text, string always) => AmLive.Senses.Analyze(text, always); + [JSExport] internal static string SenseCatalogue() => AmLive.Senses.Reference(); + } + + public static partial class RegionsJs + { + [JSExport] internal static string Analyze(string text) => Regions.Analyze(text); + } + + public static partial class NumbersJs + { + [JSExport] + internal static string Describe(string text, int digits, int numberBase, string other) => + Numbers.Describe(text, digits, numberBase, other); + + [JSExport] internal static string Factor(string text) => Numbers.Factor(text); + [JSExport] internal static string FromBase(string digits, int numberBase) => Numbers.FromBase(digits, numberBase); + } + + public static partial class MatricesJs + { + [JSExport] internal static string Analyze(string a, string b) => Matrices.Analyze(a, b); + [JSExport] internal static string Power(int n) => Matrices.Power(n); + } + + public static partial class MotionJs + { + [JSExport] + internal static string Derive(string lagrangian, string[] coords, string[] rates, string[] kinds, + string[] parameters, double[] values) => + Motion.Derive(lagrangian, coords, rates, kinds, parameters, values); + + [JSExport] internal static double[] Step(double[] state, double dt, int steps) => Motion.Step(state, dt, steps); + [JSExport] internal static double[] Energies(double[] state) => Motion.Energies(state); + } +} diff --git a/live/README.md b/live/README.md new file mode 100644 index 0000000000..632503003f --- /dev/null +++ b/live/README.md @@ -0,0 +1,57 @@ +# AngouriMath Live + +[AngouriMath](https://github.com/asc-community/AngouriMath) running in the browser as WebAssembly, with +no server. It has nine pages, each a formula box, and the library computes every answer on them in a +Web Worker. It is served at [am.angouri.org/live](https://am.angouri.org/live/), the web app of +[AngouriMath#1692](https://github.com/asc-community/AngouriMath/issues/1692). + +| Page | What the library does there | +|---|---| +| Waves | checks the units of a wave's frequency formula (`MathS.Dimensions.Of`), differentiates the surface, prints GLSL and HLSL (`MathS.Shaders`); the page runs the GLSL | +| Representations | one formula as text, Unicode, LaTeX, SymPy, expanded, factorised, its tree, a shader and a picture; `MathS.AreEqual` against a second formula | +| Shapes | an implicit surface, ray-marched with its exact gradient and Hessian | +| Calculus | derivatives, an antiderivative, roots, extrema and inflections by solving, limits, Taylor polynomials, an area | +| Logic | a truth table, the simplified form, a Karnaugh map, a circuit, a Venn diagram; signals read through a catalogue of senses | +| Regions | a statement in x and y as a region on the GPU, its boundaries intersected exactly; a set on the number line | +| Motion | a Lagrangian checked for units, its equations of motion derived, then integrated and drawn | +| Numbers | exact values, a thousand digits, primality, factors, other bases, the complex plane | +| Matrices | determinant, inverse, reduced row echelon form, powers, eigenvalues and eigenvectors | + +## Build and run + +`dotnet fsi amsite.fsx build`, at the root of this repository, publishes it and copies it to +`.output/final/live`, with the rest of the site. It needs only the .NET 10 SDK: no workload, and no +Node. To run it alone: + +```sh +dotnet publish -c Release -o ../.output/live +python serve.py ../.output/live/wwwroot 5288 # http://127.0.0.1:5288 +``` + +A page opened from disk cannot load WebAssembly modules. `serve.py` is a static server with the MIME +types WebAssembly and ES modules need. + +## How it is put together + +- `AmLive.csproj` uses `Microsoft.NET.Sdk.WebAssembly`, without Blazor, and the `AngouriMath` package, + so the page shows a released version of the library. The kernel is kept whole + (`TrimmerRootAssembly`), and the framework is trimmed. There is no AOT. +- `Demos/*.cs` are the engines, one per page, each returning JSON. `Demos/Common.cs` holds what they + share: parsing with a readable error, LaTeX, sampling, intervals, the real points of a solution set. +- `Program.cs` is the list of `[JSExport]` entry points, one class per page. +- `wwwroot/am-worker.js` loads the runtime in a module Web Worker. `wwwroot/am.js` queues calls to it, + and stops and restarts the worker when a call runs past its timeout, so a long simplification never + freezes the page. +- `wwwroot/app.js` is the shell. A tab is a module in `wwwroot/views/` with `mount(section, am)`, + loaded the first time it opens. `wwwroot/shared.js` has the DOM, WebGL and LaTeX helpers. +- The page is plain ES modules and one stylesheet, with no framework and no build step. MathJax, which + renders the LaTeX, is loaded from cdnjs. It is the only third-party load. + +A new page is a `Demos/X.cs`, an `XJs` class in `Program.cs`, a `wwwroot/views/x.js`, and a line each in +`app.js` and `index.html`. + +## When the library is released + +Raise the `AngouriMath` version in `AmLive.csproj`, as the quickstart names the release. +[AngouriMath#2296](https://github.com/asc-community/AngouriMath/issues/2296) has the payload and the +load time of the kernel under WebAssembly. diff --git a/live/serve.py b/live/serve.py new file mode 100644 index 0000000000..0833f51f3f --- /dev/null +++ b/live/serve.py @@ -0,0 +1,27 @@ +"""Serves a published wwwroot with the MIME types WebAssembly and ES modules need. + +usage: python serve.py +""" +import functools +import http.server +import sys + +root, port = sys.argv[1], int(sys.argv[2]) + + +class Handler(http.server.SimpleHTTPRequestHandler): + extensions_map = { + **http.server.SimpleHTTPRequestHandler.extensions_map, + ".wasm": "application/wasm", + ".js": "text/javascript", + ".mjs": "text/javascript", + ".json": "application/json", + ".html": "text/html", + } + + def end_headers(self): + self.send_header("Cache-Control", "no-store") + super().end_headers() + + +http.server.ThreadingHTTPServer(("127.0.0.1", port), functools.partial(Handler, directory=root)).serve_forever() diff --git a/live/wwwroot/am-worker.js b/live/wwwroot/am-worker.js new file mode 100644 index 0000000000..e7e50451d4 --- /dev/null +++ b/live/wwwroot/am-worker.js @@ -0,0 +1,31 @@ +// Loads the .NET runtime and AngouriMath in this worker and answers calls from am.js. +import { dotnet } from './framework/dotnet.js'; + +let api = null; +const started = performance.now(); + +self.onmessage = ({ data }) => { + const { id, cls, method, args } = data; + try { + const value = api[cls][method](...args); + postMessage({ type: 'result', id, ok: true, value: ArrayBuffer.isView(value) ? Array.from(value) : value }); + } catch (e) { + postMessage({ type: 'result', id, ok: false, error: String(e?.message || e) }); + } +}; + +try { + const runtime = await dotnet + .withModuleConfig({ + onDownloadResourceProgress(loaded, total) { postMessage({ type: 'progress', loaded, total }); }, + }) + .create(); + const exports = await runtime.getAssemblyExports(runtime.getConfig().mainAssemblyName); + api = exports.AmLive; + const bytes = performance.getEntriesByType('resource') + .filter((e) => e.name.includes('/framework/')) + .reduce((sum, e) => sum + (e.transferSize || 0), 0); + postMessage({ type: 'ready', seconds: (performance.now() - started) / 1000, bytes }); +} catch (e) { + postMessage({ type: 'failed', error: String(e?.message || e) }); +} diff --git a/live/wwwroot/am.js b/live/wwwroot/am.js new file mode 100644 index 0000000000..2d50603614 --- /dev/null +++ b/live/wwwroot/am.js @@ -0,0 +1,89 @@ +// AngouriMath runs in a worker, so a long simplification never freezes the page, and a call that +// runs away can be stopped: the worker is terminated and started again. + +export function createAngouri(onStatus) { + let worker, ready = false, restarted = false, failure = null; + // The worker answers in order, so the first call queued is the one it is working on. A call is + // timed from then, not from when it joined the queue behind another, and the calls behind one + // that runs away are sent again to the new worker instead of failing with it. + const queue = []; + let nextId = 1; + + function start() { + ready = false; + worker = new Worker(new URL('./am-worker.js', import.meta.url), { type: 'module' }); + worker.onmessage = ({ data }) => { + if (data.type === 'progress') onStatus({ state: 'loading', ...data }); + else if (data.type === 'ready') { + ready = true; + queue.forEach(post); + time(); + // What the demos left in the old worker is gone; restarted tells them to work it out + // again, with calls that go behind the ones already waiting. + onStatus({ state: 'ready', restarted, ...data }); + restarted = false; + } else if (data.type === 'failed') { + failure = data.error; + onStatus({ state: 'failed', error: data.error }); + failAll(data.error); + } else if (data.type === 'result') { + const call = queue[0]; + if (call?.id !== data.id) return; + queue.shift(); + clearTimeout(call.timer); + if (data.ok) call.resolve(data.value); + else call.reject(new Error(data.error)); + time(); + } + }; + worker.onerror = (e) => { + const message = e.message || 'the worker stopped'; + if (!ready) failure = message; + onStatus({ state: 'failed', error: message }); + failAll(`AngouriMath stopped: ${message}`); + }; + } + + const post = ({ id, cls, method, args }) => worker.postMessage({ id, cls, method, args }); + + function time() { + const call = queue[0]; + if (!ready || !call || call.timer) return; + call.timer = setTimeout(() => { + queue.shift(); + const reason = `AngouriMath worked on this for more than ${call.timeout / 1000} s, so it was stopped and restarted.`; + call.reject(new Error(reason)); + restarted = true; + worker.terminate(); + onStatus({ state: 'restarting', reason }); + start(); + }, call.timeout); + } + + function failAll(reason) { + for (const call of queue.splice(0)) { + clearTimeout(call.timer); + call.reject(new Error(reason)); + } + } + + /** Calls AmLive..(...args) in the worker. */ + function call(cls, method, args = [], { timeout = 20000 } = {}) { + if (failure) return Promise.reject(new Error(failure)); + return new Promise((resolve, reject) => { + const call = { id: nextId++, cls, method, args, timeout, resolve, reject, timer: 0 }; + queue.push(call); + if (ready) { + post(call); + time(); + } + }); + } + + start(); + return { + call, + /** For the exports that return JSON. */ + json: async (cls, method, args, options) => JSON.parse(await call(cls, method, args, options)), + }; +} diff --git a/live/wwwroot/app.js b/live/wwwroot/app.js new file mode 100644 index 0000000000..f8b898dc41 --- /dev/null +++ b/live/wwwroot/app.js @@ -0,0 +1,68 @@ +import { createAngouri } from './am.js'; + +// Each demo is a module with mount(section, am) returning { show(), hide() }, and restarted() if it +// keeps something in the worker that a restart loses; it is loaded the first time its tab opens. +const VIEWS = { + waves: () => import('./views/waves.js'), + forms: () => import('./views/representations.js'), + shapes: () => import('./views/shapes.js'), + calculus: () => import('./views/calculus.js'), + logic: () => import('./views/logic.js'), + regions: () => import('./views/regions.js'), + motion: () => import('./views/motion.js'), + numbers: () => import('./views/numbers.js'), + matrices: () => import('./views/matrices.js'), +}; + +const runtime = document.getElementById('runtime'); +const am = createAngouri((status) => { + runtime.dataset.state = status.state; + if (status.state === 'loading') runtime.textContent = `Loading AngouriMath: ${status.loaded} of ${status.total} files`; + else if (status.state === 'ready') { + const size = status.bytes > 0 ? `, ${(status.bytes / 1e6).toFixed(1)} MB` : ''; + runtime.textContent = `AngouriMath ready in ${status.seconds.toFixed(1)} s${size}, running in this tab`; + runtime.title = 'AngouriMath runs here as WebAssembly, in a background worker. Nothing is sent to a server.'; + if (status.restarted) for (const { view } of mounted.values()) view?.restarted?.(); + } else if (status.state === 'restarting') runtime.textContent = 'Restarting AngouriMath'; + else if (status.state === 'failed') runtime.textContent = `AngouriMath could not start: ${status.error}`; +}); + +const mounted = new Map(); +let current = null; + +// A hash is the tab's name, optionally with a query a view reads when shown: #matrices?a=... +const route = () => location.hash.slice(1).split('?')[0]; + +async function show(name) { + if (!VIEWS[name]) name = 'waves'; + for (const a of document.querySelectorAll('#tabs a')) { + const here = a.getAttribute('href') === `#${name}`; + a.setAttribute('aria-current', here ? 'page' : 'false'); + // The bar scrolls sideways when the tabs do not fit; keep the open one in sight. + if (here) a.scrollIntoView({ block: 'nearest', inline: 'nearest' }); + } + if (current === name) return; + if (current) { + const old = mounted.get(current); + old.section.hidden = true; + old.view?.hide(); + } + current = name; + let entry = mounted.get(name); + if (!entry) { + const section = document.createElement('section'); + section.className = 'view'; + section.id = `view-${name}`; + document.getElementById('views').append(section); + entry = { section, view: null }; + mounted.set(name, entry); + const module = await VIEWS[name](); + entry.view = module.mount(section, am); + } + if (current !== name) return; + entry.section.hidden = false; + entry.view.show(); +} + +addEventListener('hashchange', () => show(route())); +show(route()); diff --git a/live/wwwroot/index.html b/live/wwwroot/index.html new file mode 100644 index 0000000000..4ac76594cf --- /dev/null +++ b/live/wwwroot/index.html @@ -0,0 +1,29 @@ + + + + + +AngouriMath Live + + + + +
+ AngouriMath live + +

Loading AngouriMath as WebAssembly…

+
+
+ + + diff --git a/live/wwwroot/shared.js b/live/wwwroot/shared.js new file mode 100644 index 0000000000..fa1b67f122 --- /dev/null +++ b/live/wwwroot/shared.js @@ -0,0 +1,221 @@ +// Helpers the demos share: DOM, WebGL, LaTeX through MathJax, and the panel's parts. + +export const $ = (root, selector) => root.querySelector(selector); + +export function html(root, markup) { + root.innerHTML = markup; + return root; +} + +export function escapeHtml(s) { + return String(s).replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]); +} + +/** Reads a CSS custom property, so canvas drawing follows the theme. */ +export function token(name) { + return getComputedStyle(document.documentElement).getPropertyValue(name).trim(); +} + +export function debounce(fn, ms) { + let t = 0; + return (...args) => { clearTimeout(t); t = setTimeout(() => fn(...args), ms); }; +} + +// ---------------------------------------------------------------- panel parts + +export function setChip(chip, kind, text) { + chip.dataset.kind = kind; + chip.textContent = text; +} + +/** Fills a .presets group; returns a function that marks one as pressed (or none). */ +export function presets(group, items, onPick) { + group.replaceChildren(...items.map((item) => { + const b = document.createElement('button'); + b.type = 'button'; + b.textContent = item.label; + b.setAttribute('aria-pressed', 'false'); + b.addEventListener('click', () => onPick(item)); + return b; + })); + return (label) => { + for (const b of group.children) b.setAttribute('aria-pressed', String(b.textContent === label)); + }; +} + +/** Wires a GLSL/HLSL code block: tabs, copy button. Returns set(glsl, hlsl, note). */ +export function codeBlock(root) { + const state = { glsl: '', hlsl: '', tab: 'glsl' }; + const pre = $(root, 'pre'), glslTab = $(root, '[data-tab="glsl"]'), hlslTab = $(root, '[data-tab="hlsl"]'); + const copy = $(root, '[data-copy]'), note = $(root, '[data-note]'); + const render = () => { + glslTab.setAttribute('aria-selected', String(state.tab === 'glsl')); + hlslTab.setAttribute('aria-selected', String(state.tab === 'hlsl')); + pre.textContent = state[state.tab]; + }; + glslTab.addEventListener('click', () => { state.tab = 'glsl'; render(); }); + hlslTab.addEventListener('click', () => { state.tab = 'hlsl'; render(); }); + copy.addEventListener('click', async () => { + try { + await navigator.clipboard.writeText(pre.textContent); + copy.textContent = 'Copied'; + } catch { + getSelection().selectAllChildren(pre); + copy.textContent = 'Selected'; + } + setTimeout(() => { copy.textContent = 'Copy'; }, 1500); + }); + return (glsl, hlsl, text) => { + state.glsl = glsl; + state.hlsl = hlsl; + if (text !== undefined && note) note.textContent = text; + render(); + }; +} + +export const CODE_BLOCK = ` +
+ + + +
+

+
`;
+
+/** Collapsible panel header. */
+export function collapsible(panel) {
+  const button = $(panel, '[data-collapse]');
+  button.addEventListener('click', () => {
+    const collapsed = panel.classList.toggle('collapsed');
+    button.textContent = collapsed ? 'Show' : 'Hide';
+    button.setAttribute('aria-expanded', String(!collapsed));
+  });
+}
+
+// ---------------------------------------------------------------- LaTeX
+
+let mathjax = null;
+
+function loadMathJax() {
+  if (!mathjax) {
+    window.MathJax = { svg: { fontCache: 'local' }, startup: { typeset: false } };
+    mathjax = new Promise((resolve, reject) => {
+      const s = document.createElement('script');
+      s.src = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/3.2.2/es5/tex-svg.min.js';
+      s.async = true;
+      // Nodes are placed by hand rather than typeset in the page, so MathJax's stylesheet
+      // (which hides the assistive MathML copy) has to be added by hand too.
+      s.onload = () => window.MathJax.startup.promise
+        .then(() => document.head.append(window.MathJax.svgStylesheet()))
+        .then(resolve, reject);
+      s.onerror = () => reject(new Error('MathJax did not load'));
+      document.head.append(s);
+    });
+  }
+  return mathjax;
+}
+
+/** Renders LaTeX into el; until MathJax is there (or if it never comes) the source shows. */
+export function tex(el, latex, display = true) {
+  el.dataset.tex = latex || '';
+  if (!latex) {
+    el.textContent = '–';
+    return;
+  }
+  if (!el.firstElementChild || el.firstElementChild.tagName !== 'MJX-CONTAINER') {
+    el.innerHTML = `${escapeHtml(latex)}`;
+  }
+  loadMathJax()
+    .then(() => window.MathJax.tex2svgPromise(latex, { display }))
+    .then((node) => { if (el.dataset.tex === latex) el.replaceChildren(node); })
+    .catch(() => { if (el.dataset.tex === latex) el.innerHTML = `${escapeHtml(latex)}`; });
+}
+
+// ---------------------------------------------------------------- WebGL
+
+export function compileShader(gl, type, src) {
+  const s = gl.createShader(type);
+  gl.shaderSource(s, src);
+  gl.compileShader(s);
+  if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) {
+    const log = gl.getShaderInfoLog(s);
+    gl.deleteShader(s);
+    throw new Error(log);
+  }
+  return s;
+}
+
+/** Links a program; its uniforms are in .loc by name (arrays without [0]). */
+export function linkProgram(gl, vsSrc, fsSrc, attrib = 'aPos') {
+  const p = gl.createProgram();
+  const vs = compileShader(gl, gl.VERTEX_SHADER, vsSrc), fs = compileShader(gl, gl.FRAGMENT_SHADER, fsSrc);
+  gl.attachShader(p, vs);
+  gl.attachShader(p, fs);
+  gl.bindAttribLocation(p, 0, attrib);
+  gl.linkProgram(p);
+  gl.deleteShader(vs);
+  gl.deleteShader(fs);
+  if (!gl.getProgramParameter(p, gl.LINK_STATUS)) {
+    const log = gl.getProgramInfoLog(p);
+    gl.deleteProgram(p);
+    throw new Error(log);
+  }
+  const loc = {};
+  const n = gl.getProgramParameter(p, gl.ACTIVE_UNIFORMS);
+  for (let i = 0; i < n; i++) {
+    const name = gl.getActiveUniform(p, i).name.replace(/\[0\]$/, '');
+    loc[name] = gl.getUniformLocation(p, name);
+  }
+  return { program: p, loc };
+}
+
+/** A vertex array holding one triangle that covers the screen. */
+export function fullscreenTriangle(gl) {
+  const vao = gl.createVertexArray();
+  gl.bindVertexArray(vao);
+  gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());
+  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW);
+  gl.enableVertexAttribArray(0);
+  gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
+  gl.bindVertexArray(null);
+  return vao;
+}
+
+export const FULLSCREEN_VS = `#version 300 es
+in vec2 aPos;
+out vec2 vNdc;
+void main() { vNdc = aPos; gl_Position = vec4(aPos, 0.0, 1.0); }
+`;
+
+/** Matches the canvas's drawing buffer to its size on screen; returns [width, height]. */
+export function fitCanvas(canvas, maxDpr = 1.75) {
+  const dpr = Math.min(devicePixelRatio || 1, maxDpr);
+  const w = Math.max(1, Math.round(canvas.clientWidth * dpr)), h = Math.max(1, Math.round(canvas.clientHeight * dpr));
+  if (canvas.width !== w || canvas.height !== h) { canvas.width = w; canvas.height = h; }
+  return [w, h];
+}
+
+/** A requestAnimationFrame loop that runs only while started. */
+export function loop(frame) {
+  let id = 0, last = 0;
+  const tick = (now) => {
+    const dt = last ? Math.min((now - last) / 1000, 0.1) : 0;
+    last = now;
+    frame(dt, now);
+    id = requestAnimationFrame(tick);
+  };
+  return {
+    start() { if (!id) { last = 0; id = requestAnimationFrame(tick); } },
+    stop() { cancelAnimationFrame(id); id = 0; },
+  };
+}
+
+/** Rgb in 0..1 from a CSS colour token, for shaders. */
+export function rgb(name) {
+  const probe = document.createElement('span');
+  probe.style.color = token(name);
+  document.body.append(probe);
+  const m = getComputedStyle(probe).color.match(/[\d.]+/g).map(Number);
+  probe.remove();
+  return [m[0] / 255, m[1] / 255, m[2] / 255];
+}
diff --git a/live/wwwroot/style.css b/live/wwwroot/style.css
new file mode 100644
index 0000000000..098aeabc81
--- /dev/null
+++ b/live/wwwroot/style.css
@@ -0,0 +1,439 @@
+/* Layout: a slim top bar with one tab per demo; each demo either fills the window with its
+   picture and floats a chart-legend panel over it, or reads as a document of cards. */
+:root {
+  --bar: 52px;
+  --bg: #eef3f5;
+  --surface: #ffffff;
+  --panel: rgba(247, 250, 251, 0.9);
+  --ink: #0f2531;
+  --ink-soft: #4a616d;
+  --rule: rgba(15, 37, 49, 0.14);
+  --field: #ffffff;
+  --accent: #0a6a85;
+  --accent-ink: #ffffff;
+  --ok: #17703f;
+  --bad: #b3261e;
+  --warn: #8a5800;
+  --code: rgba(15, 37, 49, 0.06);
+  --shadow: rgba(4, 16, 24, 0.22);
+  --plot-1: #0a6a85;
+  --plot-2: #c2410c;
+  --plot-3: #7c3aed;
+  --plot-4: #15803d;
+  --plot-5: #b45309;
+  --font-display: ui-serif, "Iowan Old Style", "Palatino Linotype", Palatino, Georgia, serif;
+  --font-body: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", sans-serif;
+  --font-mono: ui-monospace, "Cascadia Code", "SF Mono", Menlo, Consolas, monospace;
+}
+@media (prefers-color-scheme: dark) {
+  :root:not([data-theme="light"]) {
+    --bg: #06121a;
+    --surface: #0b1b25;
+    --panel: rgba(8, 21, 30, 0.88);
+    --ink: #e2edf2;
+    --ink-soft: #93abb7;
+    --rule: rgba(226, 237, 242, 0.14);
+    --field: #0d2230;
+    --accent: #5dc2dc;
+    --accent-ink: #062029;
+    --ok: #5cc98c;
+    --bad: #ff8b80;
+    --warn: #f0b954;
+    --code: rgba(226, 237, 242, 0.07);
+    --shadow: rgba(0, 0, 0, 0.45);
+    --plot-1: #5dc2dc;
+    --plot-2: #fb923c;
+    --plot-3: #c4b5fd;
+    --plot-4: #6ee7a0;
+    --plot-5: #fcd34d;
+    color-scheme: dark;
+  }
+}
+:root[data-theme="dark"] {
+  --bg: #06121a;
+  --surface: #0b1b25;
+  --panel: rgba(8, 21, 30, 0.88);
+  --ink: #e2edf2;
+  --ink-soft: #93abb7;
+  --rule: rgba(226, 237, 242, 0.14);
+  --field: #0d2230;
+  --accent: #5dc2dc;
+  --accent-ink: #062029;
+  --ok: #5cc98c;
+  --bad: #ff8b80;
+  --warn: #f0b954;
+  --code: rgba(226, 237, 242, 0.07);
+  --shadow: rgba(0, 0, 0, 0.45);
+  --plot-1: #5dc2dc;
+  --plot-2: #fb923c;
+  --plot-3: #c4b5fd;
+  --plot-4: #6ee7a0;
+  --plot-5: #fcd34d;
+  color-scheme: dark;
+}
+
+/* Classes that set display would otherwise beat the hidden attribute. */
+[hidden] { display: none !important; }
+
+html, body { height: 100%; }
+body {
+  margin: 0;
+  overflow: hidden;
+  background: var(--bg);
+  color: var(--ink);
+  font: 14px/1.45 var(--font-body);
+}
+button, input, select { font: inherit; color: inherit; }
+button { cursor: pointer; }
+:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+
+/* ------------------------------------------------------------------ top bar */
+.bar {
+  position: fixed;
+  top: 0;
+  left: 0;
+  right: 0;
+  z-index: 5;
+  height: calc(var(--bar) + env(safe-area-inset-top, 0px));
+  box-sizing: border-box;
+  padding-top: env(safe-area-inset-top, 0px);
+  padding-left: max(16px, env(safe-area-inset-left, 0px));
+  padding-right: max(16px, env(safe-area-inset-right, 0px));
+  display: flex;
+  align-items: center;
+  gap: 18px;
+  background: var(--surface);
+  border-bottom: 1px solid var(--rule);
+}
+.brand { flex: none; font: italic 19px/1 var(--font-display); white-space: nowrap; }
+a.brand { color: inherit; text-decoration: none; }
+.brand span { color: var(--accent); }
+.tabs {
+  flex: 1;
+  min-width: 0;
+  display: flex;
+  gap: 2px;
+  overflow-x: auto;
+  scrollbar-width: none;
+}
+.tabs a {
+  flex: none;
+  padding: 6px 11px;
+  border-radius: 999px;
+  color: var(--ink-soft);
+  text-decoration: none;
+  font-size: 13.5px;
+}
+.tabs a:hover { color: var(--ink); background: var(--code); }
+.tabs a[aria-current="page"] { color: var(--accent-ink); background: var(--accent); }
+.runtime {
+  flex: none;
+  margin: 0;
+  max-width: 34ch;
+  font-size: 12px;
+  color: var(--ink-soft);
+  text-align: right;
+  white-space: nowrap;
+  overflow: hidden;
+  text-overflow: ellipsis;
+}
+.runtime[data-state="ready"]::before { content: "● "; color: var(--ok); }
+.runtime[data-state="failed"]::before, .runtime[data-state="restarting"]::before { content: "● "; color: var(--bad); }
+@media (max-width: 1180px) {
+  .runtime { max-width: 16ch; }
+}
+@media (max-width: 760px) {
+  .runtime { display: none; }
+  .brand span { display: none; }
+}
+
+/* ------------------------------------------------------------------ views */
+.view {
+  position: fixed;
+  top: calc(var(--bar) + env(safe-area-inset-top, 0px));
+  left: 0;
+  right: 0;
+  bottom: 0;
+}
+.view.doc {
+  overflow-y: auto;
+  padding-left: max(16px, env(safe-area-inset-left, 0px));
+  padding-right: max(16px, env(safe-area-inset-right, 0px));
+  padding-block: 20px calc(32px + env(safe-area-inset-bottom, 0px));
+}
+.stage {
+  position: absolute;
+  inset: 0;
+  width: 100%;
+  height: 100%;
+  display: block;
+  touch-action: none;
+  cursor: grab;
+}
+.stage:active { cursor: grabbing; }
+
+.panel {
+  position: absolute;
+  top: 16px;
+  left: calc(16px + env(safe-area-inset-left, 0px));
+  width: min(410px, calc(100% - 32px));
+  max-height: calc(100% - 32px - env(safe-area-inset-bottom, 0px));
+  overflow: auto;
+  box-sizing: border-box;
+  padding: 16px 18px 18px;
+  display: grid;
+  gap: 14px;
+  align-content: start;
+  background: var(--panel);
+  color: var(--ink);
+  border: 1px solid var(--rule);
+  border-radius: 14px;
+  box-shadow: 0 14px 44px var(--shadow);
+  -webkit-backdrop-filter: blur(14px) saturate(1.15);
+  backdrop-filter: blur(14px) saturate(1.15);
+}
+.panel > * { min-width: 0; }
+.panel-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; }
+.panel.collapsed .panel-body { display: none; }
+.panel-body { display: grid; gap: 14px; min-width: 0; }
+.panel-body > * { min-width: 0; }
+@media (max-width: 640px) {
+  .panel {
+    top: auto;
+    left: 0;
+    right: 0;
+    bottom: 0;
+    width: auto;
+    max-height: 58%;
+    border-radius: 14px 14px 0 0;
+    border-width: 1px 0 0;
+    padding-left: max(16px, env(safe-area-inset-left, 0px));
+    padding-right: max(16px, env(safe-area-inset-right, 0px));
+    padding-bottom: calc(16px + env(safe-area-inset-bottom, 0px));
+  }
+}
+
+.eyebrow {
+  margin: 0 0 2px;
+  font-size: 11px;
+  letter-spacing: 0.08em;
+  text-transform: uppercase;
+  color: var(--ink-soft);
+}
+h1, h2 { margin: 0; font-weight: 500; text-wrap: balance; }
+h1 { font: italic 500 22px/1.2 var(--font-display); }
+h2 { font: italic 500 18px/1.25 var(--font-display); }
+.lede { margin: 0; color: var(--ink-soft); max-width: 70ch; }
+
+.ghost {
+  flex: none;
+  padding: 4px 10px;
+  border: 1px solid var(--rule);
+  border-radius: 999px;
+  background: transparent;
+  font-size: 12.5px;
+}
+.ghost:hover { background: var(--code); }
+
+.section { display: grid; gap: 8px; padding-top: 12px; border-top: 1px solid var(--rule); }
+.field-label { display: block; margin: 0; font-size: 12.5px; color: var(--ink-soft); }
+.formula {
+  display: flex;
+  align-items: center;
+  gap: 8px;
+  padding: 8px 10px;
+  background: var(--field);
+  border: 1px solid var(--rule);
+  border-radius: 9px;
+}
+.formula:focus-within { border-color: var(--accent); }
+.formula > span { flex: none; font: italic 17px var(--font-display); color: var(--ink-soft); }
+.formula textarea { resize: none; padding: 0; overflow: hidden; }
+.formula:has(textarea) { position: relative; align-items: flex-start; }
+.formula:has(textarea) > span { line-height: 21px; }
+.formula .gutter { flex: none; min-width: 2ch; padding-right: 8px; border-right: 1px solid var(--rule); text-align: right; font: 12px/21px var(--font-mono); color: var(--ink-soft); user-select: none; }
+.formula .gutter .wrap { color: var(--accent); }
+.formula .measure { position: absolute; top: 0; left: 0; visibility: hidden; pointer-events: none; white-space: pre-wrap; overflow-wrap: break-word; font: 14px/21px var(--font-mono); }
+.formula input, .formula textarea {
+  flex: 1;
+  min-width: 0;
+  border: 0;
+  outline: 0;
+  background: transparent;
+  color: var(--ink);
+  font: 14px/21px var(--font-mono);
+}
+.presets { display: flex; flex-wrap: wrap; gap: 6px; }
+.presets button {
+  padding: 3px 10px;
+  border: 1px solid var(--rule);
+  border-radius: 999px;
+  background: transparent;
+  font-size: 12.5px;
+}
+.presets button:hover { background: var(--code); }
+.presets button[aria-pressed="true"] { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
+.note { margin: 0; font-size: 12.5px; color: var(--ink-soft); }
+.note:empty { display: none; }
+
+.status { display: flex; align-items: center; justify-content: space-between; gap: 8px; flex-wrap: wrap; }
+.chip {
+  display: inline-flex;
+  align-items: center;
+  gap: 6px;
+  padding: 2px 10px;
+  border-radius: 999px;
+  font-size: 12.5px;
+  font-weight: 600;
+  white-space: nowrap;
+  color: var(--ink-soft);
+  background: var(--code);
+}
+.chip::before { content: ""; width: 7px; height: 7px; border-radius: 50%; background: currentColor; }
+.chip[data-kind="ok"] { color: var(--ok); background: color-mix(in srgb, var(--ok) 13%, transparent); }
+.chip[data-kind="bad"] { color: var(--bad); background: color-mix(in srgb, var(--bad) 13%, transparent); }
+.chip[data-kind="warn"] { color: var(--warn); background: color-mix(in srgb, var(--warn) 15%, transparent); }
+.timing { font-size: 12px; color: var(--ink-soft); font-variant-numeric: tabular-nums; }
+.error { margin: 0; font-size: 12.5px; color: var(--bad); overflow-wrap: anywhere; }
+.error:empty { display: none; }
+
+.checks { display: grid; grid-template-columns: auto 1fr; gap: 4px 12px; margin: 0; }
+.checks dt { font-size: 12.5px; color: var(--ink-soft); }
+.checks dd { margin: 0; min-width: 0; font: 12.5px/1.45 var(--font-mono); overflow-wrap: anywhere; }
+
+.slider { display: grid; grid-template-columns: 1fr auto; gap: 2px 12px; align-items: baseline; }
+.slider label { font-size: 12.5px; color: var(--ink-soft); }
+.slider output { font-size: 12.5px; font-variant-numeric: tabular-nums; }
+.slider input { grid-column: 1 / -1; width: 100%; margin: 0; accent-color: var(--accent); }
+.row { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
+
+.stats { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; margin: 0; }
+.stats div { min-width: 0; }
+.stats dt { font-size: 11.5px; color: var(--ink-soft); }
+.stats dd { margin: 0; font-size: 15px; font-variant-numeric: tabular-nums; }
+
+.tex { min-width: 0; overflow-x: auto; overflow-y: hidden; padding: 2px 0; }
+.tex mjx-container { margin: 0 !important; }
+.tex svg { max-width: none; }
+.tex-raw { font: 12.5px var(--font-mono); color: var(--ink-soft); overflow-wrap: anywhere; }
+.labelled { display: grid; gap: 2px; }
+.labelled > span { font-size: 11.5px; color: var(--ink-soft); }
+
+.code summary { cursor: pointer; font-size: 12.5px; color: var(--ink-soft); }
+.code-bar { display: flex; align-items: center; gap: 6px; margin: 8px 0 6px; flex-wrap: wrap; }
+.code-bar [role="tab"] {
+  padding: 2px 10px;
+  border: 1px solid var(--rule);
+  border-radius: 999px;
+  background: transparent;
+  font-size: 12px;
+}
+.code-bar [role="tab"][aria-selected="true"] { background: var(--ink); color: var(--surface); border-color: var(--ink); }
+.code-bar .ghost { margin-left: auto; font-size: 12px; }
+pre {
+  margin: 0;
+  max-height: 260px;
+  overflow: auto;
+  padding: 10px 12px;
+  background: var(--code);
+  border-radius: 8px;
+  font: 11.5px/1.5 var(--font-mono);
+  white-space: pre;
+  tab-size: 4;
+}
+.foot { margin: 0; font-size: 11.5px; color: var(--ink-soft); }
+
+/* ------------------------------------------------------------------ document views */
+.doc-inner { max-width: 1120px; margin: 0 auto; display: grid; gap: 18px; }
+.doc-head { display: grid; gap: 10px; }
+.cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 330px), 1fr)); gap: 14px; }
+.card {
+  min-width: 0;
+  display: grid;
+  gap: 8px;
+  align-content: start;
+  padding: 14px 16px;
+  background: var(--surface);
+  border: 1px solid var(--rule);
+  border-radius: 12px;
+}
+.card > * { min-width: 0; }
+.card.wide { grid-column: 1 / -1; }
+.card h3 { margin: 0; font-size: 12px; letter-spacing: 0.06em; text-transform: uppercase; color: var(--ink-soft); font-weight: 600; }
+.card canvas { width: 100%; display: block; border-radius: 8px; }
+.scroll-x { overflow-x: auto; }
+
+table.truth { border-collapse: collapse; font: 12.5px var(--font-mono); font-variant-numeric: tabular-nums; }
+table.truth th, table.truth td { padding: 3px 10px; text-align: center; border-bottom: 1px solid var(--rule); }
+table.truth th { color: var(--ink-soft); font-weight: 600; }
+table.truth td.t { color: var(--ok); font-weight: 700; }
+table.truth td.f { color: var(--ink-soft); }
+table.truth tr.hit td { background: color-mix(in srgb, var(--ok) 10%, transparent); }
+table.truth tr.dc td { opacity: .5; }
+table.truth td.x { color: var(--ink-soft); }
+table.senses { border-collapse: collapse; font-size: 13px; }
+table.senses th, table.senses td { padding: 4px 10px 4px 0; text-align: left; border-bottom: 1px solid var(--rule); vertical-align: top; }
+table.senses th { color: var(--ink-soft); font-weight: 600; }
+table.senses td:nth-child(-n+2) { font-family: var(--font-mono); white-space: nowrap; }
+.contents { display: contents; }
+svg.pla .w { fill: none; stroke: var(--ink); stroke-width: 1.5; }
+svg.pla .d { fill: var(--ink); }
+svg.pla .g { fill: var(--surface); stroke: var(--ink); stroke-width: 1.6; }
+svg.pla .k { fill: var(--code); stroke: var(--rule); }
+svg.pla .kt, svg.pla .lit text { font: 12px var(--font-mono); fill: var(--ink); }
+svg.pla .lit { cursor: pointer; }
+svg.pla .lit rect { fill: var(--code); stroke: var(--rule); stroke-width: 1; }
+svg.pla .lit:hover rect, svg.pla .lit:focus-visible rect { stroke: var(--ink-soft); stroke-width: 1.6; }
+svg.pla .lit:focus { outline: none; }
+svg.pla .lit.on rect { stroke: var(--accent); stroke-width: 3; }
+svg.pla .lit.on text { font-weight: 700; }
+svg.pla .w.on { stroke: var(--accent); stroke-width: 2.5; }
+svg.pla .d.on { fill: var(--accent); }
+svg.pla .g.on { fill: color-mix(in srgb, var(--accent) 22%, var(--surface)); stroke: var(--accent); stroke-width: 2.2; }
+svg.pla .out { font: 13px var(--font-mono); fill: var(--ink-soft); }
+svg.pla .out.on { font-weight: 700; fill: var(--accent); }
+.pla-state { font: 13px var(--font-mono); color: var(--ink); }
+.pla-state.fail { font-family: inherit; color: var(--bad); font-weight: 600; }
+table.truth tr.current td { background: color-mix(in srgb, var(--accent) 24%, transparent); font-weight: 700; }
+.check { padding: 4px 0 6px; border-bottom: 1px solid var(--rule); }
+.check .foot.pass { color: var(--ok); }
+.check .foot.fail { color: var(--bad); font-weight: 600; }
+.output-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 300px), 1fr)); gap: 14px; align-items: start; }
+.card h3 .name { text-transform: none; letter-spacing: 0; font-family: var(--font-mono); }
+.condition { display: flex; align-items: center; gap: 14px; padding: 4px 0; border-bottom: 1px solid var(--rule); }
+.condition > span { flex: none; min-width: 150px; font: 13px var(--font-mono); color: var(--ink-soft); }
+table.senses em { font-style: normal; font-size: 11px; color: var(--accent); }
+details.catalogue summary { cursor: pointer; font-size: 13px; color: var(--ink-soft); }
+details.catalogue .foot { margin: 8px 0; }
+.catalogue-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 6px 18px; }
+.catalogue-grid div { font-size: 13px; color: var(--ink-soft); }
+.catalogue-grid span { display: block; font-size: 11.5px; }
+.catalogue-grid button { font: 13px var(--font-mono); background: none; border: 0; padding: 0; color: var(--ink); text-decoration: underline dotted var(--ink-soft); text-underline-offset: 3px; }
+.catalogue-grid button:hover { color: var(--accent); }
+
+svg text { font-family: var(--font-body); }
+.diagram { width: 100%; height: auto; display: block; }
+
+/* ------------------------------------------------------------------ forms, numbers, matrices */
+.forms { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 300px), 1fr)); gap: 12px 18px; }
+.forms .alternatives { grid-column: 1 / -1; }
+.forms ol { margin: 0; padding: 0; list-style: none; display: grid; gap: 2px; }
+.forms li { display: flex; align-items: center; gap: 10px; min-width: 0; }
+.forms li > span { flex: none; width: 1.4em; text-align: right; font-size: 12px; color: var(--ink-soft); }
+.forms li > .tex { flex: 1; }
+pre.digits { white-space: pre-wrap; overflow-wrap: anywhere; font-size: 12.5px; }
+.chips { display: flex; flex-wrap: wrap; gap: 4px; }
+.chips:empty { display: none; }
+.chips span { padding: 1px 7px; border-radius: 999px; background: var(--code); font: 12px var(--font-mono); font-variant-numeric: tabular-nums; }
+table.bases { border-collapse: collapse; width: 100%; }
+table.bases th { padding: 4px 12px 4px 0; text-align: left; font-size: 12px; font-weight: 600; color: var(--ink-soft); white-space: nowrap; vertical-align: top; }
+table.bases td { padding: 4px 0; font: 12.5px/1.5 var(--font-mono); overflow-wrap: anywhere; word-break: break-all; }
+table.bases tr + tr > * { border-top: 1px solid var(--rule); }
+.from-base { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; font-size: 13px; color: var(--ink-soft); }
+.from-base input, .from-base select { padding: 5px 8px; border: 1px solid var(--rule); border-radius: 8px; background: var(--field); font: 14px var(--font-mono); }
+.from-base input { width: 12ch; }
+svg.plane { max-width: 360px; }
+.eigen { display: grid; gap: 6px; }
+.eigen-row { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 260px), 1fr)); gap: 4px 18px; align-items: center; padding: 4px 0; border-bottom: 1px solid var(--rule); }
+.card canvas[data-picture] { height: min(420px, 90vw); }
+.checks.facts dd { font-family: var(--font-body); font-variant-numeric: tabular-nums; }
diff --git a/live/wwwroot/views/calculus.js b/live/wwwroot/views/calculus.js
new file mode 100644
index 0000000000..9648b89fd4
--- /dev/null
+++ b/live/wwwroot/views/calculus.js
@@ -0,0 +1,453 @@
+import { $, html, setChip, presets, collapsible, tex, token, debounce, fitCanvas } from '../shared.js';
+import { niceStep } from './representations.js';
+
+const PRESETS = [
+  { label: 'Cubic', formula: 'x^3 - 3x + 1', area: [-1, 1], range: [-3, 3],
+    note: 'Three real roots, which AngouriMath gives exactly by Cardano’s formula: through complex cube roots, although all three are real.' },
+  { label: 'sin(x)/x', formula: 'sin(x) / x', area: [0, 2], point: 1, range: [-16, 16], at: '0',
+    note: 'Roots come back as a family over every whole n, 2πn and π + 2πn, with the condition that excludes 0. The antiderivative is the sine integral Si.' },
+  { label: 'Gaussian bump', formula: 'x e^(-x^2)', area: [0, 2], range: [-3, 3] },
+  { label: 'ln(x)/x', formula: 'ln(x) / x', area: [1, 4], point: 1, range: [-1, 9], at: '0', note: 'Defined for x > 0 only; the plot leaves the rest empty.' },
+  { label: 'Double well', formula: 'x^4 - 2x^2', area: [-1, 1], range: [-2.2, 2.2] },
+  { label: 'e^x', formula: 'e^x', area: [0, 1], range: [-3, 2.5], at: '-oo', note: 'Its own derivative and antiderivative; the Taylor polynomials are the familiar partial sums.' },
+  { label: 'Asymptotes', formula: '(2x^2 - 1) / (x^2 - 4)', area: [-1, 1], range: [-6, 6], at: '2',
+    note: 'Poles at x = ±2, where the one-sided limits go off to opposite infinities, and the line y = 2 that f approaches at both ends.' },
+  { label: 'A hole', formula: '(x^2 - 1) / (x - 1)', area: [-1, 2], range: [-3, 3], at: '1',
+    note: 'The line y = x + 1 with the point x = 1 taken out: f has no value there, but its limit is 2.' },
+];
+
+const CURVES = [
+  { key: 'f', label: 'f', color: '--plot-1', on: true },
+  { key: 'd1', label: 'f′', color: '--plot-2', on: true },
+  { key: 'd2', label: 'f″', color: '--plot-3', on: false },
+  { key: 'F', label: '∫ f dx', color: '--plot-4', on: false },
+  { key: 'taylor', label: 'Taylor', color: '--plot-5', on: true, dashed: true },
+];
+
+const MARKUP = `
+
+`;
+
+export function mount(section, am) {
+  html(section, MARKUP);
+  const canvas = $(section, 'canvas'), chip = $(section, '[data-chip]');
+  collapsible($(section, '.panel'));
+  const view = { x0: -6, x1: 6, y0: -3, y1: 3, fitted: false };
+  const data = { n: 0, curves: null, points: { roots: [], extrema: [], inflections: [] }, limits: null };
+  const ui = { order: 3, point: 0, a: -1, b: 1, formula: '' };
+  let range = [-6, 6];
+  // Shows [a, b] in the part of the canvas the panel does not cover.
+  function frame(r = [-6, 6]) {
+    range = r;
+    const covered = canvas.clientWidth > 900 ? 450 / canvas.clientWidth : 0;
+    view.x1 = r[1];
+    view.x0 = r[0] - (r[1] - r[0]) * covered / (1 - covered);
+    view.fitted = false;
+  }
+  const shown = Object.fromEntries(CURVES.map((c) => [c.key, c.on]));
+
+  // ------------------------------------------------------------ toggles
+  for (const c of CURVES) {
+    const label = document.createElement('label');
+    label.style.cssText = 'display:inline-flex;gap:5px;align-items:center;font-size:12.5px';
+    label.innerHTML = `${c.label}`;
+    label.querySelector('input').addEventListener('change', (e) => { shown[c.key] = e.target.checked; draw(); });
+    $(section, '[data-toggles]').append(label);
+  }
+
+  // ------------------------------------------------------------ drawing
+  const toX = (x, w) => (x - view.x0) / (view.x1 - view.x0) * w;
+  const toY = (y, h) => h - (y - view.y0) / (view.y1 - view.y0) * h;
+
+  function draw() {
+    const [w, h] = fitCanvas(canvas, 2);
+    const ctx = canvas.getContext('2d'), s = w / canvas.clientWidth;
+    ctx.fillStyle = token('--surface');
+    ctx.fillRect(0, 0, w, h);
+    ctx.font = `${11 * s}px ${token('--font-body')}`;
+    ctx.lineWidth = s;
+    ctx.strokeStyle = token('--rule');
+    ctx.fillStyle = token('--ink-soft');
+    const sx = niceStep((view.x1 - view.x0) / 10), sy = niceStep((view.y1 - view.y0) / 8);
+    for (let x = Math.ceil(view.x0 / sx) * sx; x <= view.x1; x += sx) {
+      ctx.beginPath(); ctx.moveTo(toX(x, w), 0); ctx.lineTo(toX(x, w), h); ctx.stroke();
+      ctx.fillText(+x.toFixed(6) + '', toX(x, w) + 3 * s, Math.min(Math.max(toY(0, h) + 13 * s, 13 * s), h - 4 * s));
+    }
+    for (let y = Math.ceil(view.y0 / sy) * sy; y <= view.y1; y += sy) {
+      ctx.beginPath(); ctx.moveTo(0, toY(y, h)); ctx.lineTo(w, toY(y, h)); ctx.stroke();
+      if (Math.abs(y) > sy / 2) ctx.fillText(+y.toFixed(6) + '', Math.min(Math.max(toX(0, w) + 4 * s, 4 * s), w - 40 * s), toY(y, h) - 3 * s);
+    }
+    ctx.strokeStyle = token('--ink-soft');
+    ctx.lineWidth = 1.3 * s;
+    ctx.beginPath(); ctx.moveTo(toX(0, w), 0); ctx.lineTo(toX(0, w), h); ctx.moveTo(0, toY(0, h)); ctx.lineTo(w, toY(0, h)); ctx.stroke();
+    if (!data.curves) return;
+    const n = data.n, xs = (i) => view.x0 + (view.x1 - view.x0) * i / (n - 1);
+
+    // The area under f between a and b.
+    const f = data.curves.f;
+    ctx.fillStyle = token('--plot-1');
+    ctx.globalAlpha = 0.16;
+    ctx.beginPath();
+    let open = false;
+    for (let i = 0; i < n; i++) {
+      const x = xs(i);
+      if (x < Math.min(ui.a, ui.b) || x > Math.max(ui.a, ui.b) || !Number.isFinite(f[i])) {
+        if (open) { ctx.lineTo(toX(xs(i - 1), w), toY(0, h)); ctx.closePath(); open = false; }
+        continue;
+      }
+      if (!open) { ctx.moveTo(toX(x, w), toY(0, h)); open = true; }
+      ctx.lineTo(toX(x, w), toY(f[i], h));
+    }
+    if (open) { ctx.lineTo(toX(xs(n - 1), w), toY(0, h)); ctx.closePath(); }
+    ctx.fill();
+    ctx.globalAlpha = 1;
+
+    for (const c of CURVES) {
+      if (!shown[c.key]) continue;
+      const ys = data.curves[c.key];
+      ctx.strokeStyle = token(c.color);
+      ctx.lineWidth = (c.key === 'f' ? 2.6 : 1.8) * s;
+      ctx.setLineDash(c.dashed ? [7 * s, 5 * s] : []);
+      ctx.beginPath();
+      let pen = false, prev = null;
+      for (let i = 0; i < n; i++) {
+        const y = ys[i];
+        // Break the line at gaps and at jumps across poles.
+        if (y === null || !Number.isFinite(y) || (prev !== null && Math.abs(y - prev) > 4 * (view.y1 - view.y0))) { pen = false; prev = y ?? null; continue; }
+        const px = toX(xs(i), w), py = toY(y, h);
+        pen ? ctx.lineTo(px, py) : ctx.moveTo(px, py);
+        pen = true;
+        prev = y;
+      }
+      ctx.stroke();
+    }
+    ctx.setLineDash([]);
+
+    // What the limits say: dashed asymptotes, and open dots where f has no value but a limit.
+    const lim = data.limits;
+    if (lim && shown.f) {
+      ctx.save();
+      ctx.setLineDash([6 * s, 5 * s]);
+      ctx.strokeStyle = token('--ink-soft');
+      ctx.lineWidth = 1.3 * s;
+      // An asymptote at one end is drawn over that half; one the two ends share, across.
+      const mid = (view.x0 + view.x1) / 2;
+      const shared = lim.minus.kind === 'value' && lim.plus.kind === 'value' && lim.minus.value === lim.plus.value;
+      for (const [end, from, to] of [[lim.minus, view.x0, shared ? view.x1 : mid], [lim.plus, shared ? view.x1 : mid, view.x1]]) {
+        if (end.kind !== 'value') continue;
+        ctx.beginPath(); ctx.moveTo(toX(from, w), toY(end.value, h)); ctx.lineTo(toX(to, w), toY(end.value, h)); ctx.stroke();
+      }
+      for (const p of lim.points)
+        if ([p.left.kind, p.right.kind].some((k) => k === '+oo' || k === '-oo')) {
+          ctx.beginPath(); ctx.moveTo(toX(p.x, w), 0); ctx.lineTo(toX(p.x, w), h); ctx.stroke();
+        }
+      ctx.restore();
+      for (const p of lim.points) {
+        if (p.defined) continue;
+        for (const side of [p.left, p.right]) {
+          if (side.kind !== 'value') continue;
+          ctx.beginPath(); ctx.arc(toX(p.x, w), toY(side.value, h), 5 * s, 0, Math.PI * 2);
+          ctx.fillStyle = token('--surface'); ctx.fill();
+          ctx.lineWidth = 2 * s; ctx.strokeStyle = token('--plot-1'); ctx.stroke();
+        }
+      }
+    }
+
+    // Special points, placed on f by interpolating its samples.
+    const fAt = (x) => {
+      const t = (x - view.x0) / (view.x1 - view.x0) * (n - 1), i = Math.floor(t);
+      if (i < 0 || i >= n - 1 || !Number.isFinite(f[i]) || !Number.isFinite(f[i + 1])) return null;
+      return f[i] + (f[i + 1] - f[i]) * (t - i);
+    };
+    const mark = (kind, x, y) => {
+      const px = toX(x, w), py = toY(y, h), r = 5 * s;
+      ctx.beginPath();
+      if (kind === 'roots') ctx.arc(px, py, r, 0, Math.PI * 2);
+      else if (kind === 'extrema') { ctx.moveTo(px, py - r * 1.3); ctx.lineTo(px + r * 1.3, py); ctx.lineTo(px, py + r * 1.3); ctx.lineTo(px - r * 1.3, py); ctx.closePath(); }
+      else ctx.rect(px - r, py - r, 2 * r, 2 * r);
+      ctx.fillStyle = token('--surface');
+      ctx.fill();
+      ctx.lineWidth = 2 * s;
+      ctx.strokeStyle = token('--ink');
+      ctx.stroke();
+    };
+    for (const kind of ['roots', 'extrema', 'inflections'])
+      for (const x of data.points[kind]) {
+        if (x < view.x0 || x > view.x1) continue;
+        const y = kind === 'roots' ? 0 : fAt(x);
+        if (y !== null) mark(kind, x, y);
+      }
+    if (shown.taylor) {
+      const y = fAt(ui.point);
+      if (y !== null) {
+        ctx.fillStyle = token('--plot-5');
+        ctx.beginPath(); ctx.arc(toX(ui.point, w), toY(y, h), 4 * s, 0, Math.PI * 2); ctx.fill();
+      }
+    }
+  }
+
+  // ------------------------------------------------------------ AngouriMath calls
+  let sampling = false, resample = false;
+  async function sample() {
+    if (!ui.formula) return;
+    if (sampling) { resample = true; return; }
+    sampling = true;
+    const n = Math.max(200, Math.min(1200, Math.round(canvas.clientWidth)));
+    try {
+      const flat = await am.call('CalculusJs', 'Sample', [view.x0, view.x1, n, ui.order]);
+      const keys = ['f', 'd1', 'd2', 'F', 'taylor'];
+      data.n = n;
+      data.curves = Object.fromEntries(keys.map((k, j) => [k, flat.slice(j * n, (j + 1) * n)]));
+      if (!view.fitted) fitY();
+      draw();
+    } catch { /* the status line says what happened */ }
+    sampling = false;
+    if (resample) { resample = false; sample(); }
+  }
+
+  function fitY() {
+    const n = data.n, ys = data.curves.f.filter((y, i) => Number.isFinite(y) && view.x0 + (view.x1 - view.x0) * i / (n - 1) >= range[0]).sort((a, b) => a - b);
+    if (!ys.length) return;
+    // Fit to the part of f in the visible range, ignoring the extreme tenth at each end.
+    let lo = ys[Math.floor(ys.length * 0.08)], hi = ys[Math.ceil(ys.length * 0.92) - 1];
+    lo = Math.min(lo, 0); hi = Math.max(hi, 0);
+    if (hi - lo < 1e-6) { lo -= 1; hi += 1; }
+    const pad = (hi - lo) * 0.35;
+    view.y0 = lo - pad; view.y1 = hi + pad;
+    view.fitted = true;
+  }
+
+  async function taylor() {
+    const err = $(section, '[data-taylor-error]');
+    try {
+      const r = await am.json('CalculusJs', 'Taylor', [ui.formula, ui.point]);
+      if (!r.ok) { err.textContent = r.error; tex($(section, '[data-taylor]'), ''); }
+      else { err.textContent = ''; data.taylor = r.latex; showTaylor(); }
+    } catch (e) { err.textContent = e.message; }
+    sample();
+  }
+  function showTaylor() {
+    const latex = data.taylor?.[ui.order];
+    tex($(section, '[data-taylor]'), latex ? `p_{${ui.order}}(x) = ${latex}` : '');
+  }
+
+  async function area() {
+    try {
+      const r = await am.json('CalculusJs', 'Area', [Math.min(ui.a, ui.b), Math.max(ui.a, ui.b)]);
+      const lo = Math.min(ui.a, ui.b), hi = Math.max(ui.a, ui.b);
+      tex($(section, '[data-area]'), r.exactLatex
+        ? `\\int_{${lo}}^{${hi}} f\\,dx = ${r.exactLatex}${r.exactValue !== null && r.exactLatex !== String(r.exactValue) ? ` \\approx ${r.exactValue.toPrecision(10)}` : ''}`
+        : '');
+      $(section, '[data-area-check]').textContent = r.numeric === null
+        ? 'The midpoint rule finds no finite area here.'
+        : `${r.exactLatex ? 'Check by' : 'No exact antiderivative was found; by'} the midpoint rule with 4000 steps: ${r.numeric.toPrecision(10)}.`;
+    } catch (e) { $(section, '[data-area-check]').textContent = e.message; }
+    draw();
+  }
+
+  // A limit as LaTeX: lim f(x) = its value, or why there is none.
+  function limitTex(where, l) {
+    const lhs = `\\lim_{${where}} f(x)`;
+    if (l.kind === 'none') return `${lhs} &\\text{ does not exist}`;
+    if (l.kind === 'unknown') return `${lhs} &\\text{: AngouriMath leaves it open}`;
+    return `${lhs} &= ${l.kind === '+oo' ? '+\\infty' : l.kind === '-oo' ? '-\\infty' : l.latex}`;
+  }
+  const sameLimit = (a, b) => a.kind === b.kind && a.latex === b.latex;
+  // One line for a two-sided limit, two where the sides differ.
+  const pointTex = (at, left, right) => sameLimit(left, right)
+    ? [limitTex(`x \\to ${at}`, left)]
+    : [limitTex(`x \\to ${at}^-`, left), limitTex(`x \\to ${at}^+`, right)];
+  const aligned = (lines) => `\\begin{aligned}${lines.join(' \\\\ ')}\\end{aligned}`;
+
+  async function limits(text, mine) {
+    let r;
+    try { r = await am.json('CalculusJs', 'Limits', [text]); } catch { return; }
+    if (mine !== generation || !r.ok) return;
+    data.limits = r;
+    const lines = [limitTex('x \\to -\\infty', r.minus), limitTex('x \\to +\\infty', r.plus)];
+    const kinds = [];
+    for (const p of r.points) {
+      lines.push(...pointTex(p.at, p.left, p.right));
+      const pole = [p.left.kind, p.right.kind].some((k) => k === '+oo' || k === '-oo');
+      const kind = pole ? 'a pole' : !sameLimit(p.left, p.right) ? 'a jump' : p.defined ? 'no break' : 'a hole';
+      kinds.push(`${kind} at x = ${+p.x.toFixed(6)}`);
+    }
+    tex($(section, '[data-limits]'), aligned(lines));
+    $(section, '[data-limits-note]').textContent = r.points.length
+      ? `A denominator or a logarithm’s argument is zero there: ${kinds.join(', ')}.`
+      : 'No denominator or logarithm of f is zero near the origin.';
+    draw();
+  }
+
+  async function limitAt() {
+    const err = $(section, '[data-limit-error]'), box = $(section, '[data-limit-at]');
+    if (!ui.formula) return;
+    let r;
+    try { r = await am.json('CalculusJs', 'LimitAt', [ui.formula, atIn.value]); } catch (e) { err.textContent = e.message; return; }
+    if (!r.ok) { err.textContent = r.error; tex(box, ''); return; }
+    err.textContent = '';
+    if (r.limit) {
+      const at = r.at.trim().startsWith('-') ? r.at : `+${r.at}`;
+      tex(box, aligned([limitTex(`x \\to ${at}`, r.limit)]));
+      return;
+    }
+    const lines = pointTex(r.at, r.left, r.right);
+    lines.push(r.value === null ? `f(${r.at}) &\\text{ has no value}` : `f(${r.at}) &= ${+r.value.toPrecision(12)}`);
+    tex(box, aligned(lines));
+  }
+
+  let generation = 0;
+  async function analyze(text) {
+    const mine = ++generation, t0 = performance.now();
+    setChip(chip, '', 'Working');
+    let r;
+    try {
+      r = await am.json('CalculusJs', 'Analyze', [text], { timeout: 25000 });
+    } catch (e) {
+      if (mine === generation) { setChip(chip, 'bad', 'AngouriMath stopped'); $(section, '[data-error]').textContent = e.message; }
+      return;
+    }
+    if (mine !== generation) return;
+    $(section, '[data-timing]').textContent = `${Math.round(performance.now() - t0)} ms`;
+    if (!r.ok) { setChip(chip, 'warn', 'Not a function of x yet'); $(section, '[data-error]').textContent = r.error; return; }
+    setChip(chip, 'ok', 'Derived, integrated and solved');
+    $(section, '[data-error]').textContent = '';
+    ui.formula = text;
+    view.fitted = false;
+    data.limits = null;
+    limits(text, mine);
+    limitAt();
+    tex($(section, '[data-d1]'), r.d1);
+    tex($(section, '[data-d2]'), r.d2);
+    tex($(section, '[data-integral]'), r.integral || '\\text{no antiderivative found}');
+    for (const kind of ['roots', 'extrema', 'inflections']) {
+      const s = r[kind];
+      data.points[kind] = s.points.filter((x) => x !== null);
+      tex($(section, `[data-${kind}]`), s.latex.length > 600 ? '' : s.latex || '\\text{none found}');
+      const near = data.points[kind].filter((x) => Math.abs(x) < 50);
+      $(section, `[data-${kind}-n]`).textContent = !s.latex ? ''
+        : `${s.latex.length > 600 ? `${s.text.slice(0, 120)}… ` : ''}${near.length} real ${near.length === 1 ? 'value' : 'values'} between −50 and 50${s.numerical ? ', found by a numerical search where there is no closed form, so not necessarily all' : ''}${near.length && near.length <= 6 ? `: ${near.map((x) => x.toPrecision(6)).join(', ')}` : ''}.`;
+    }
+    await taylor();
+    area();
+  }
+
+  // ------------------------------------------------------------ controls
+  const input = $(section, '#calc-input'), note = $(section, '[data-note]'), atIn = $(section, '#calc-at');
+  const orderIn = $(section, '#calc-order'), pointIn = $(section, '#calc-point'), aIn = $(section, '#calc-a'), bIn = $(section, '#calc-b');
+  const syncLabels = () => {
+    $(section, '[data-order-out]').textContent = ui.order;
+    $(section, '[data-point-out]').textContent = ui.point;
+    $(section, '[data-a-out]').textContent = ui.a;
+    $(section, '[data-b-out]').textContent = ui.b;
+  };
+  function pick(p) {
+    input.value = p.formula;
+    note.textContent = p.note || '';
+    press(p.label);
+    ui.a = p.area[0]; ui.b = p.area[1]; ui.point = p.point ?? 0;
+    atIn.value = p.at ?? '+oo';
+    aIn.value = ui.a * 10; bIn.value = ui.b * 10; pointIn.value = ui.point * 8;
+    frame(p.range);
+    syncLabels();
+    analyze(p.formula);
+  }
+  const press = presets($(section, '.presets'), PRESETS, pick);
+  const later = debounce(() => analyze(input.value), 500);
+  input.addEventListener('input', () => { press(null); note.textContent = ''; later(); });
+  orderIn.addEventListener('input', () => { ui.order = +orderIn.value; syncLabels(); showTaylor(); sample(); });
+  const laterTaylor = debounce(() => taylor(), 250);
+  pointIn.addEventListener('input', () => { ui.point = +pointIn.value / 8; syncLabels(); laterTaylor(); });
+  const laterArea = debounce(() => area(), 150);
+  atIn.addEventListener('input', debounce(() => limitAt(), 400));
+  aIn.addEventListener('input', () => { ui.a = +aIn.value / 10; syncLabels(); draw(); laterArea(); });
+  bIn.addEventListener('input', () => { ui.b = +bIn.value / 10; syncLabels(); draw(); laterArea(); });
+
+  // Pan by dragging, zoom with the wheel around the pointer, reset on double-click.
+  let drag = null;
+  canvas.addEventListener('pointerdown', (e) => { drag = { x: e.clientX, y: e.clientY }; canvas.setPointerCapture(e.pointerId); });
+  canvas.addEventListener('pointermove', (e) => {
+    if (!drag) return;
+    const dx = (e.clientX - drag.x) / canvas.clientWidth * (view.x1 - view.x0), dy = (e.clientY - drag.y) / canvas.clientHeight * (view.y1 - view.y0);
+    view.x0 -= dx; view.x1 -= dx; view.y0 += dy; view.y1 += dy;
+    drag = { x: e.clientX, y: e.clientY };
+    draw();
+    sample();
+  });
+  canvas.addEventListener('pointerup', () => { drag = null; });
+  canvas.addEventListener('wheel', (e) => {
+    e.preventDefault();
+    const r = canvas.getBoundingClientRect(), k = Math.exp(e.deltaY * 0.0012);
+    const cx = view.x0 + (e.clientX - r.left) / r.width * (view.x1 - view.x0), cy = view.y1 - (e.clientY - r.top) / r.height * (view.y1 - view.y0);
+    view.x0 = cx + (view.x0 - cx) * k; view.x1 = cx + (view.x1 - cx) * k;
+    view.y0 = cy + (view.y0 - cy) * k; view.y1 = cy + (view.y1 - cy) * k;
+    draw();
+    sample();
+  }, { passive: false });
+  canvas.addEventListener('dblclick', () => { frame(range); sample(); });
+  const ro = new ResizeObserver(() => { draw(); sample(); });
+  ro.observe(canvas);
+
+  pick(PRESETS[0]);
+  return { show: () => draw(), hide() {}, restarted: () => analyze(input.value) };
+}
diff --git a/live/wwwroot/views/logic.js b/live/wwwroot/views/logic.js
new file mode 100644
index 0000000000..5643900bcd
--- /dev/null
+++ b/live/wwwroot/views/logic.js
@@ -0,0 +1,651 @@
+import { $, html, escapeHtml, setChip, presets, tex, token, debounce, fitCanvas } from '../shared.js';
+import { truthTable } from './representations.js';
+
+const LOGIC = [
+  { label: 'Redundant', formula: '(a and b) or (a and not b) or (c and a)',
+    note: 'Three terms that say only “a”. AngouriMath and the Karnaugh map both find it.' },
+  { label: 'Majority', formula: '(a and b) or (b and c) or (a and c)', note: 'True when at least two of three are true.' },
+  { label: 'Parity', formula: 'a xor b xor c', note: 'A checkerboard on the map: no two true cells touch, so nothing groups.' },
+  { label: 'Four inputs', formula: '(a and not c) or (b and c and d) or (not a and not b and not d) or (a and b and c)',
+    note: 'Groups that wrap around the edges of the map, which is a torus.' },
+  { label: 'Syllogism', formula: '((a implies b) and (b implies c)) implies (a implies c)', note: 'A tautology: true in every row.' },
+  { label: 'Knights and knaves', puzzle: ['A', 'B'],
+    formula: 'not (A xor not B) and not (B xor not (A xor B))',
+    note: 'A says “B is a knave.” B says “A and I are of the same kind.” Knights always tell the truth and knaves always lie, so “X says S” means X and S have the same truth value: not (X xor S).' },
+  { label: 'Three islanders', puzzle: ['A', 'B', 'C'],
+    formula: 'not (A xor (not A and not B and not C)) and not (B xor ((A and not B and not C) or (not A and B and not C) or (not A and not B and C)))',
+    note: 'A says “We are all knaves.” B says “Exactly one of us is a knight.” C says nothing.' },
+];
+
+const SETS = [
+  { label: '(A ∪ B) ∩ C', formula: '(A \\/ B) /\\ C' },
+  { label: 'Symmetric difference', formula: '(A \\ B) \\/ (B \\ A)', note: 'AngouriMath simplifies the logic to A xor B.' },
+  { label: 'All three', formula: 'A /\\ B /\\ C' },
+  { label: 'In exactly one', formula: '(A \\ (B \\/ C)) \\/ (B \\ (A \\/ C)) \\/ (C \\ (A \\/ B))' },
+  { label: 'De Morgan', formula: 'A \\ (B \\/ C)', note: 'Read as logic: a and not (b or c), which is a and not b and not c.' },
+];
+
+// Each line is an output, Name = formula, in a sense like the inputs, or a condition, Name = a
+// comparison of real numbers. An output may use the ones above it.
+const SENSES = [
+  { label: 'Two standards, one window', formula: 'On_heating = Occupied and Closed_window and not Open_window',
+    note: 'The window reaches the controller twice: as KNX DPT 1.009, where 1 means closed, and as DPT 1.019, where 1 means open. It is one condition, so one letter, and the second test is the first one again.' },
+  { label: 'Dry-run protection', formula: 'On_pump = On_request and (NotEmpty_tank or Full_tank)', always: 'On_pump implies NotEmpty_tank',
+    note: 'A full tank is not empty. That is a fact about tanks, not about logic, so AngouriMath’s simplification keeps the Full test; the catalogue knows it, and the minimal form drops it. The always line mentions the output, so it is a design check: the pump never runs on an empty tank.' },
+  { label: 'Held up', formula: 'Alarm_hover = Up and not Held and not Falling', always: '(Up and not Falling) implies Held',
+    note: 'Something up that is not falling is held up by something. The alarm asks for a row that cannot happen, so with good sensors it never fires, and that same row is the fault alarm.' },
+  { label: 'Lamp and horn', formula: 'On_lamp = Alarm and not Shelved and not Suppressed\nOn_horn = On_lamp and Unacknowledged and Unsilenced',
+    always: 'On_horn implies On_lamp',
+    note: 'Two outputs, and a design check that the horn never sounds without the lamp. ANSI/ISA-18.2 keeps acknowledgement, shelving and suppression on channels of their own beside the alarm: the lamp shows an alarm that is neither shelved nor suppressed, and the horn, built on the lamp, sounds until it is acknowledged or silenced.' },
+  { label: 'Valve position',
+    formula: 'On_openlamp = Near_openend and Far_closedend\nOn_closedlamp = Near_closedend and Far_openend\nAlarm_discrepancy = (Open_cmd and not On_openlamp) or (Closed_cmd and not On_closedlamp)',
+    always: 'not (Near_openend and Near_closedend); not (On_openlamp and On_closedlamp)',
+    note: 'A valve reports its position with two proximity switches, one at each end of its travel: two channels, as IEC 61850 keeps them, because mid-travel both read far. The stem cannot be at both ends, so each lamp needs one switch, the discrepancy alarm (commanded one way and not there, held past the travel time) follows, and both switches near is IEC 61850’s bad state, the fault alarm. The second line is a design check: the two lamps never light together.' },
+  { label: 'Two-channel safety door', formula: 'On_press = On_request and Closed_a and not Open_b and NoFault_press',
+    always: 'Closed_a xor Open_b',
+    note: 'Channel a is a normally-open contact (1 = closed) and channel b a normally-closed one (1 = open), so healthy contacts always differ. With that invariant one channel is enough, which is safe only because the fault alarm watches it: a safety relay runs on both channels and trips on a discrepancy.' },
+  { label: 'Window and handle',
+    formula: 'Open_heatingvalve = Heating_mode and Occupied_room and Closed_window and Closed_handle\nOpen_coolingvalve = Cooling_mode and Occupied_room and Closed_window and Closed_handle',
+    always: 'Open_window implies Open_handle',
+    note: 'A window cannot open while its handle is turned to closed, so a closed handle already means a closed window, and a contact reading open behind a closed handle means one of the two is wrong. Heating / Cooling is one bit for two alternatives (KNX DPT 1.100).' },
+  { label: 'Stack light',
+    formula: 'On_green = Running_filler and not (Blocked_filler or Starved_filler) and InSpecification_scale and NoFault_filler and Remote_filler\nOn_amber = Blocked_filler or Starved_filler\nOn_red = Fault_filler or OutOfSpecification_scale',
+    always: '(Blocked_filler or Starved_filler or Fault_filler) implies Stopped_filler; not (On_green and On_red); not (On_green and On_amber); On_green or On_amber or On_red',
+    note: 'A filler’s stack light from six signals, too many for a Karnaugh map. PackML suspends a machine that is blocked or starved, and a fault stops it, so a running filler is none of those and green needs three tests, not six. The last three lines are design checks: green never lights with red or amber, but the last one fails, and the checks card says when the light is dark.' },
+  { label: 'Kettle',
+    formula: 'above_boilingpoint = T > 100\ntoo_hot = T > 120\nOn_heater = On_kettle and not above_boilingpoint\nAlarm_dry = On_kettle and too_hot and above_boilingpoint',
+    always: 'not (On_heater and Alarm_dry)',
+    note: 'Conditions on a real number. AngouriMath solves where each comparison turns, at 100 and 120, and finds that T > 120 implies T > 100, so the dry-boil alarm needs only one of them, and the design check that the heater is never on during a dry-boil alarm holds because of it. If the two are separate thermostats, the 120 °C one on without the 100 °C one means one of them is broken.' },
+  { label: 'Frost protection', formula: 'On_heater = (Occupied_room and T < 19) or (Unoccupied_room and T < 5) or T < 2',
+    note: 'Comfort heating when the room is occupied, frost protection when it is not, and a last resort below 2 °C, with the comparisons written in the formula. Each implies the next, so the minimal form needs neither the last resort nor the Unoccupied test.' },
+];
+
+const MODES = { logic: 'Logic', sets: 'Sets', senses: 'Senses' };
+
+const MARKUP = `
+
+
+
+

Boolean algebra, sets and logic puzzles

+

Logic

+
+

A formula in true-or-false variables, or a formula in sets: AngouriMath builds the truth table and simplifies it, a Karnaugh map finds the minimal sum of products, and AngouriMath checks every rewrite is equivalent by comparing truth tables.

+
+
+ + +
+

+
Waiting for AngouriMath
+

+
+
+ + + + +

The formula

+

Simplified by AngouriMath

+

Minimal sum of products

+ + + +

Karnaugh map

+

Truth table

+

Circuit for the simplified form

+ +
+
`; + +export function mount(section, am) { + section.classList.add('doc'); + html(section, MARKUP); + const input = $(section, '#logic-input'), always = $(section, '#logic-always'), chip = $(section, '[data-chip]'), note = $(section, '[data-note]'); + let mode = 'logic', current = null; + + const pressMode = presets($(section, '[data-modes]'), Object.values(MODES).map((label) => ({ label })), + (m) => setMode(Object.keys(MODES).find((k) => MODES[k] === m.label))); + let press = () => {}; + function setMode(m) { + mode = m; + pressMode(MODES[m]); + $(section, '[data-prefix]').textContent = m === 'sets' ? 'S =' : 'ƒ'; + $(section, '[data-prefix]').hidden = m === 'senses'; + gutter.hidden = m !== 'senses'; + $(section, '[data-always-row]').hidden = m !== 'senses'; + $(section, '[data-catalogue]').hidden = m !== 'senses'; + if (m === 'senses') showCatalogue(); + const list = m === 'sets' ? SETS : m === 'senses' ? SENSES : LOGIC; + press = presets($(section, '[data-presets]'), list, pick); + pick(list[0]); + } + // The formula field is a textarea so that senses mode can take one output per line; it grows + // with its text, and elsewhere Enter adds no line. In senses mode a gutter numbers each line and + // marks with ↪ each row that only continues a long one, measured on a hidden copy of the text + // laid out at the same width, so a new line and a wrapped one look different. + const gutter = $(section, '[data-gutter]'), measure = $(section, '[data-measure]'); + function fit() { + input.style.height = 'auto'; + input.style.height = `${input.scrollHeight}px`; + if (gutter.hidden) return; + measure.style.width = `${input.clientWidth}px`; + measure.replaceChildren(...input.value.split('\n').map((line) => { + const row = document.createElement('div'); + row.textContent = line || ' '; + return row; + })); + const step = parseFloat(getComputedStyle(input).lineHeight); + gutter.innerHTML = [...measure.children].map((row, i) => + `
${i + 1}
${'
↪
'.repeat(Math.max(0, Math.round(row.offsetHeight / step) - 1))}`).join(''); + } + let width = 0; + new ResizeObserver(() => { if (input.clientWidth !== width) { width = input.clientWidth; fit(); } }).observe(input.parentElement); + input.addEventListener('keydown', (e) => { if (e.key === 'Enter' && mode !== 'senses') e.preventDefault(); }); + function pick(p) { + current = p; + input.value = p.formula; + fit(); + always.value = p.always || ''; + note.textContent = p.note || ''; + press(p.label); + analyze(); + } + const later = debounce(() => { current = null; analyze(); }, 450); + let typingIn = input; + for (const field of [input, always]) { + field.addEventListener('input', () => { fit(); press(null); note.textContent = ''; later(); }); + field.addEventListener('focus', () => { typingIn = field; }); + } + + // The catalogue comes from the C# side, which reads the formula by it, so the two cannot differ. + let catalogue = null; + async function showCatalogue() { + catalogue ??= am.json('LogicJs', 'SenseCatalogue', []).then((c) => { + const sense = (name) => ``; + $(section, '[data-catalogue-grid]').innerHTML = c.pairs.map((p) => + `
${sense(p.true)} / ${sense(p.false)}${p.source ? `${escapeHtml(p.source)}` : ''}
`).join(''); + $(section, '[data-catalogue-rules]').textContent = c.exclusive.map((x) => + `Built in: ${x.a} implies ${x.notB} on any channel that has both. ${x.why}`).join(' '); + }); + try { await catalogue; } catch { catalogue = null; } + } + $(section, '[data-catalogue-grid]').addEventListener('click', (e) => { + const name = e.target.closest('[data-sense]')?.dataset.sense; + if (!name) return; + const at = typingIn.selectionStart ?? typingIn.value.length, end = typingIn.selectionEnd ?? at; + const before = typingIn.value.slice(0, at), gap = before && !/\s$/.test(before) ? ' ' : ''; + typingIn.value = before + gap + name + typingIn.value.slice(end); + typingIn.focus(); + typingIn.setSelectionRange(at + gap.length + name.length, at + gap.length + name.length); + typingIn.dispatchEvent(new Event('input')); + }); + + let generation = 0; + async function analyze() { + const mine = ++generation, t0 = performance.now(); + let r; + try { + r = mode === 'senses' + ? await am.json('LogicJs', 'Senses', [input.value, always.value]) + : await am.json('LogicJs', mode === 'sets' ? 'Venn' : 'Analyze', [input.value]); + } catch (e) { + if (mine === generation) { setChip(chip, 'bad', 'AngouriMath stopped'); $(section, '[data-error]').textContent = e.message; } + return; + } + if (mine !== generation) return; + $(section, '[data-timing]').textContent = `${Math.round(performance.now() - t0)} ms`; + if (!r.ok) { setChip(chip, 'warn', 'Not a formula yet'); $(section, '[data-error]').textContent = r.error; return; } + $(section, '[data-error]').textContent = ''; + const senses = mode === 'senses'; + for (const card of section.querySelectorAll('[data-plain]')) card.hidden = senses; + for (const card of ['[data-senses-card]', '[data-outputs]', '[data-rules-card]', '[data-pla-card]']) $(section, card).hidden = !senses; + $(section, '[data-conditions-card]').hidden = !senses || !r.conditions?.length; + $(section, '[data-checks-card]').hidden = !senses || !r.checks?.length; + if (senses) { + $(section, '[data-puzzle]').hidden = $(section, '[data-venn-card]').hidden = true; + showSenses(r); + return; + } + const vars = r.truth.vars, rows = r.truth.rows; + const count = rows.filter((row) => row[row.length - 1]).length; + setChip(chip, 'ok', count === rows.length ? 'Always true' : count === 0 ? 'Never true' : `True in ${count} of ${rows.length} rows`); + tex($(section, '[data-latex]'), r.latex); + tex($(section, '[data-simplified]'), r.simplifiedLatex); + $(section, '[data-simplified-check]').textContent = r.simplifiedEquivalent ? '✓ Equivalent: AngouriMath’s truth table of (formula xor simplified) has no true row.' : 'Not shown equivalent.'; + tex($(section, '[data-sop]'), r.sopLatex); + $(section, '[data-sop-check]').textContent = r.sopEquivalent ? '✓ Equivalent, checked the same way. Found by Quine–McCluskey with an exact cover.' : 'Not shown equivalent.'; + $(section, '[data-truth]').replaceChildren(truthTable(r.truth)); + $(section, '[data-kmap-card]').hidden = vars.length > 4; + if (vars.length <= 4) kmap($(section, '[data-kmap]'), vars, rows, r.groups); + $(section, '[data-kmap-note]').textContent = r.groups.length ? 'Each outline is one product term of the minimal sum; outlines that reach an edge continue on the opposite side.' : ''; + circuit($(section, '[data-circuit]'), r.circuit); + + const puzzle = current?.puzzle; + $(section, '[data-puzzle]').hidden = !puzzle; + if (puzzle) { + const answers = rows.filter((row) => row[row.length - 1]).map((row) => + vars.map((v, i) => `${v} is a ${row[i] ? 'knight' : 'knave'}`).join(', ')); + $(section, '[data-answer]').innerHTML = answers.length === 1 + ? `

${escapeHtml(answers[0])}.

The only row of the truth table where everything said is consistent.

` + : answers.length === 0 ? '

No assignment is consistent: the puzzle has no solution.

' + : `

${answers.length} consistent answers:

    ${answers.map((a) => `
  • ${escapeHtml(a)}
  • `).join('')}
`; + } + $(section, '[data-venn-card]').hidden = mode !== 'sets'; + if (mode === 'sets') { + venn($(section, '[data-venn]'), vars, rows); + $(section, '[data-sets]').textContent = `As sets: ${r.sets}${r.simplifiedSets && r.simplifiedSets !== r.sets ? `, which simplifies to ${r.simplifiedSets}` : ''}.`; + } + } + + // The circuit's input values, by label, so that they survive an edit of the formula. + const switched = new Map(); + function showSenses(r) { + const n = r.inputs.length, rows = r.truth.rows, possible = r.truth.possible, can = possible.filter(Boolean).length; + const every = can === rows.length, where = every ? '' : ' that can occur'; + let summary; + if (r.outputs.length === 1) { + const count = rows.filter((row, i) => possible[i] && row[n]).length; + summary = count === can ? (every ? 'Always true' : 'True in every row that can occur') + : count === 0 ? (every ? 'Never true' : 'Never true in a row that can occur') : `True in ${count} of ${can} rows${where}`; + } else + summary = `${r.outputs.length} outputs of ${n} inputs, ${every ? `all ${rows.length} rows can occur` : `${can} of ${rows.length} rows can occur`}`; + const failing = r.checks.filter((c) => !c.holds).length; + if (r.checks.length) + summary += failing ? `; ${failing} of ${r.checks.length} design checks fail` : `; ${r.checks.length === 1 ? 'the design check holds' : `all ${r.checks.length} design checks hold`}`; + setChip(chip, failing ? 'warn' : 'ok', summary); + $(section, '[data-senses]').innerHTML = sensesTable(r.senses); + conditions($(section, '[data-conditions]'), r); + $(section, '[data-outputs]').replaceChildren(...r.outputs.map((o, k) => outputCard(o, k, r))); + rules($(section, '[data-rules]'), r); + designChecks($(section, '[data-checks]'), r); + $(section, '[data-truth]').replaceChildren(truthTable(r.truth)); + const paint = pla($(section, '[data-pla]'), r.inputs, r.outputs, (i) => { + switched.set(r.inputs[i].label, !(switched.get(r.inputs[i].label) ?? false)); + simulate(); + }); + function simulate() { + const values = r.inputs.map((input) => switched.get(input.label) ?? false), results = paint(values); + const index = values.reduce((sum, v) => sum * 2 + (v ? 1 : 0), 0), state = $(section, '[data-pla-state]'); + state.classList.toggle('fail', !possible[index]); + state.textContent = possible[index] + ? r.outputs.map((o, k) => `${o.name || 'ƒ'} = ${results[k] ? 1 : 0}`).join(', ') + : 'These inputs cannot occur: the invariants rule them out, so the fault alarm is on, and the outputs are whatever the minimal forms make of a don’t-care.'; + section.querySelectorAll('[data-truth] tbody tr').forEach((tr, i) => tr.classList.toggle('current', i === index)); + } + simulate(); + } + + setMode('logic'); + return { show() {}, hide() {} }; +} + +// ---------------------------------------------------------------- senses + +function sensesTable(list) { + const body = list.map((s) => `${escapeHtml(s.word)}${s.output ? ' output' : ''}${s.negated ? 'not ' : ''}${escapeHtml(s.letter)}` + + (s.pair ? `${escapeHtml(s.pair)}${escapeHtml(s.source || '')}` + : `${s.condition ? `a condition: true when ${escapeHtml(s.condition)}` : 'not in the catalogue: a letter of its own'}`) + + '').join(''); + return `${body}
writtenreads aspairsource
`; +} + +function conditions(box, r) { + box.replaceChildren(); + for (const c of r.conditions) { + const row = document.createElement('div'); + row.className = 'condition'; + row.innerHTML = `${c.name ? escapeHtml(c.name) : 'in a formula'}
`; + tex(row.lastElementChild, c.latex, false); + box.append(row); + } + const foot = document.createElement('p'); + foot.className = 'foot'; + foot.textContent = ['Each comparison is one input, true where it holds; its negation is written turned round, as T ≤ 100 for not (T > 100). How comparisons on one number constrain each other is worked out by AngouriMath and listed with the invariants.', ...r.notes].join(' '); + box.append(foot); +} + +function designChecks(box, r) { + box.replaceChildren(); + for (const c of r.checks) { + const item = document.createElement('div'); + item.className = 'check'; + const when = c.holds ? [] : c.whenTerms; + item.innerHTML = `

` + + when.map(() => '
').join('') + (c.holds ? '' : '

'); + tex(item.children[0], c.latex); + item.children[1].textContent = c.holds + ? '✓ Holds in every row that can occur: AngouriMath’s truth table of (invariants and not check), with each output replaced by its formula, has no true row.' + : `✗ Fails in ${c.broken} of the ${c.occur} rows that can occur, exactly when ${when.length > 1 ? 'any of these holds' : 'this holds'}:`; + when.forEach((latex, i) => tex(item.children[2 + i], latex)); + if (!c.holds) item.lastElementChild.textContent = `For example: ${c.example}.`; + box.append(item); + } + const foot = document.createElement('p'); + foot.className = 'foot'; + foot.textContent = 'A line of the always field that mentions an output is a check on the design rather than a fact about the plant: it does not decide which rows can occur, it has to hold in all of them.'; + box.append(foot); +} + +function outputCard(o, k, r) { + const n = r.inputs.length, card = document.createElement('article'); + card.className = 'card wide'; + card.innerHTML = `

${o.name ? `Output ${escapeHtml(o.name)}` : 'The formula'}

+
+
+
+

In letters

+

Simplified by AngouriMath, which knows the logic but not the invariants

+

+

Minimal, using the invariants

+

+
+

+
`; + const q = (key) => card.querySelector(`[data-k="${key}"]`); + const named = (latex) => (o.nameLatex && latex ? `${o.nameLatex} = ${latex}` : latex); + tex(q('written'), named(o.latex)); + q('letters-box').hidden = o.lettersLatex === o.latex; + tex(q('letters'), named(o.lettersLatex)); + tex(q('simplified'), named(o.simplifiedLatex)); + q('simplified-check').textContent = o.simplifiedEquivalent ? '✓ Equivalent: AngouriMath’s truth table of (formula xor simplified) has no true row.' : 'Not shown equivalent.'; + tex(q('minimal'), named(o.sopLatex)); + q('minimal-check').textContent = o.sopEquivalent + ? '✓ Equal to the formula wherever the invariants hold: AngouriMath’s truth table of (formula xor minimal) and invariants has no true row. Found by Quine–McCluskey, with the rows that cannot occur as don’t-cares.' + : 'Not shown equivalent.'; + if (n <= 4) { + kmap(q('kmap'), r.truth.vars, r.truth.rows.map((row) => [...row.slice(0, n), row[n + k]]), o.groups, r.dontCares); + q('kmap-note').textContent = (o.groups.length ? 'Karnaugh map: each outline is one product term of the minimal form, and outlines that reach an edge continue on the opposite side.' : 'Karnaugh map.') + + (r.dontCares.length ? ' A dash is a row the invariants rule out, so an outline may cover it or not.' : ''); + } else + q('kmap-box').innerHTML = '

More than four inputs, so no Karnaugh map; the truth table has every row.

'; + return card; +} + +function rules(box, r) { + box.replaceChildren(); + if (!r.rules.length) { + box.innerHTML = '

None: every row can occur. Facts about the plant go in the always field, separated by semicolons, for example Running_motor implies Enabled_motor.

'; + return; + } + for (const rule of r.rules) { + const item = document.createElement('div'); + item.innerHTML = `

${rule.builtin ? `Built in. ${escapeHtml(rule.why)}` : 'Yours.'}

`; + tex(item.firstElementChild, rule.latex); + box.append(item); + } + const fault = document.createElement('div'), terms = r.faultTerms?.length > 1 ? r.faultTerms : [r.faultLatex]; + fault.innerHTML = `

Fault alarm${terms.length > 1 ? ', when any of these holds' : ''}

` + + terms.map(() => '
').join('') + '

'; + terms.forEach((latex, i) => tex(fault.children[1 + i], latex)); + fault.lastElementChild.textContent = r.faultNever ? 'The invariants hold in every row, so they rule nothing out and nothing can contradict them.' + : `True exactly in the rows the invariants rule out, so with correct signals it never fires: when it does, a sensor or its wiring is wrong.${r.faultEquivalent ? ' ✓ Equivalent to not (invariants), checked by truth table.' : ''}`; + box.append(fault); +} + +// ---------------------------------------------------------------- Karnaugh map + +const GRAY = [[0], [0, 1], [0, 1, 3, 2]]; + +function kmap(box, vars, rows, groups, dontCares = []) { + const n = vars.length, impossible = new Set(dontCares); + const rowVars = n <= 1 ? 0 : n === 2 ? 1 : n === 3 ? 1 : 2, colVars = n - rowVars; + const rowCodes = rowVars === 0 ? [0] : GRAY[rowVars], colCodes = colVars === 1 ? [0, 1] : GRAY[colVars]; + const minterm = (r, c) => (rowCodes[r] << colVars) | colCodes[c]; + const value = (m) => rows[m][n]; + // Letters label the corner as "ab \ cd"; names label the row codes and the column codes apart. + const named = vars.some((v) => v.length > 1); + const rowLabel = vars.slice(0, rowVars).join(named ? ', ' : ''), colLabel = vars.slice(rowVars).join(named ? ', ' : ''); + const C = 54, X0 = named ? Math.max(70, rowLabel.length * 7 + 16) : 70, Y0 = 46; + const W = Math.max(X0 + colCodes.length * C + 16, named ? X0 + colCodes.length * C / 2 + colLabel.length * 3.5 + 8 : 0), H = Y0 + rowCodes.length * C + 16; + const bits = (code, k) => code.toString(2).padStart(k, '0'); + const label = 'font-size="12" style="fill:var(--ink-soft)"'; + let svg = named + ? `${escapeHtml(rowLabel)}` + + `${escapeHtml(colLabel)}` + : `${escapeHtml(rowLabel)} \\ ${escapeHtml(colLabel)}`; + colCodes.forEach((code, c) => { + svg += `${bits(code, colVars)}`; + }); + rowCodes.forEach((code, r) => { + if (rowVars) svg += `${bits(code, rowVars)}`; + colCodes.forEach((_, c) => { + const m = minterm(r, c), v = !impossible.has(m) && value(m); + const fill = impossible.has(m) ? 'color-mix(in srgb, var(--ink-soft) 12%, var(--surface))' : v ? 'color-mix(in srgb, var(--ok) 16%, var(--surface))' : 'var(--surface)'; + svg += ``; + svg += `${impossible.has(m) ? '–' : v ? 1 : 0}`; + }); + }); + // A group is a product of a cyclic run of rows and a cyclic run of columns; a run that wraps + // is drawn as two pieces. + const colours = ['--plot-1', '--plot-2', '--plot-3', '--plot-4', '--plot-5']; + const runs = (indices, size) => { + const set = new Set(indices); + if (set.size === size) return [[0, size - 1]]; + let start = [...set].find((i) => !set.has((i - 1 + size) % size)); + const out = []; + let a = start, b = start; + while (set.has((b + 1) % size) && (b + 1) % size !== start) b = (b + 1) % size; + if (b >= a) out.push([a, b]); + else { out.push([a, size - 1]); out.push([0, b]); } + return out; + }; + groups.forEach((g, k) => { + const covered = (m) => (m & g.mask) === g.value; + const rs = [], cs = []; + rowCodes.forEach((_, r) => { if (colCodes.some((__, c) => covered(minterm(r, c)))) rs.push(r); }); + colCodes.forEach((_, c) => { if (rowCodes.some((__, r) => covered(minterm(r, c)))) cs.push(c); }); + const inset = 5 + 4 * (k % 4); + for (const [r0, r1] of runs(rs, rowCodes.length)) + for (const [c0, c1] of runs(cs, colCodes.length)) + svg += ``; + }); + box.innerHTML = `${svg}`; +} + +// ---------------------------------------------------------------- circuit + +function circuit(box, tree) { + if (!tree) { box.textContent = ''; return; } + const nodes = []; + let leaves = 0, depth = 0; + (function place(n, d) { + depth = Math.max(depth, d); + const node = { label: n.t, d, kids: (n.c || []).map((c) => place(c, d + 1)) }; + node.y = node.kids.length ? (node.kids[0].y + node.kids[node.kids.length - 1].y) / 2 : leaves++; + // An input's box fits its name; the columns widen so a wire leaves it before turning. + node.w = node.kids.length ? 44 : Math.max(36, n.t.length * 7 + 12); + nodes.push(node); + return node; + })(tree, 0); + const DX = Math.max(92, ...nodes.map((n) => n.w / 2 + 34)), DY = 46, W = (depth + 1) * DX + 80, H = Math.max(leaves, 1) * DY + 20; + // The output is on the right, inputs on the left. + const pos = (n) => [W - 60 - n.d * DX, n.y * DY + DY / 2 + 10]; + const stroke = 'stroke:var(--ink);stroke-width:1.6;fill:none'; + const body = 'stroke:var(--ink);stroke-width:1.6;fill:var(--surface)'; + let svg = ''; + for (const n of nodes) + n.kids.forEach((k, i) => { + const [x1, y1] = pos(n), [x2, y2] = pos(k); + const inY = y1 + (n.kids.length > 1 ? (i - (n.kids.length - 1) / 2) * 10 : 0), mid = Math.max((x1 - 22 + x2 + 22) / 2, x2 + k.w / 2 + 10); + svg += ``; + }); + const [ox, oy] = pos(nodes[nodes.length - 1]); + svg += ``; + for (const n of nodes) { + const [x, y] = pos(n); + if (!n.kids.length) { + svg += ``; + svg += `${escapeHtml(n.label)}`; + continue; + } + const g = n.label; + if (g === 'and') svg += ``; + else if (g === 'or' || g === 'xor') { + svg += ``; + if (g === 'xor') svg += ``; + } else if (g === 'not') svg += ``; + else svg += `${escapeHtml(g === 'implies' ? '→' : g)}`; + } + box.innerHTML = `${svg}`; +} + +// ---------------------------------------------------------------- circuit of several outputs + +// Two levels, as a PLA draws them: each literal once on the left with a vertical rail, an AND gate +// per product term shared by every output that uses it, a rail per term, and an OR gate per output +// with its name on the right. A term of one literal needs no AND, and an output of one term no OR. +function pla(box, inputs, outputs, onToggle) { + const n = inputs.length; + const terms = [], byKey = new Map(); + outputs.forEach((o, k) => o.groups.forEach((g) => { + const key = `${g.mask}:${g.value}`; + if (!byKey.has(key)) { + const lits = []; + for (let i = 0; i < n; i++) { + const bit = 1 << (n - 1 - i); + if (g.mask & bit) lits.push(`${i}:${g.value & bit ? 1 : 0}`); + } + byKey.set(key, { lits, outs: [] }); + terms.push(byKey.get(key)); + } + byKey.get(key).outs.push(k); + })); + const used = []; + for (let i = 0; i < n; i++) + for (const v of [1, 0]) if (terms.some((t) => t.lits.includes(`${i}:${v}`))) used.push(`${i}:${v}`); + const label = (lit) => { const [i, v] = lit.split(':').map(Number); return v ? inputs[i].label : inputs[i].opposite; }; + const ofOutput = outputs.map((_, k) => terms.filter((t) => t.outs.includes(k))); + + // Rows: each column is stacked on its own and centred on the tallest. + const PITCH = 34, PIN = 12, gap = (m) => Math.max(PITCH, m * PIN + 14); + const stack = (sizes) => { let y = 0; return sizes.map((s) => { const at = y + s / 2; y += s; return at; }).concat([y]); }; + const litYs = stack(used.map(() => PITCH)), termYs = stack(terms.map((t) => gap(t.lits.length))), outYs = stack(ofOutput.map((ts) => gap(ts.length))); + const H = Math.max(litYs.pop(), termYs.pop(), outYs.pop()) + 24; + const centre = (ys, h) => ys.map((y) => y + (H - h) / 2); + const ly = centre(litYs, used.length * PITCH), ty = centre(termYs, terms.reduce((s, t) => s + gap(t.lits.length), 0)), oy = centre(outYs, ofOutput.reduce((s, ts) => s + gap(ts.length), 0)); + + // Columns, left to right. Every wire, gate and box carries the signal it shows (l: a literal, + // t: a product term, o: an output), so that painting it is a matter of classes. + const LW = Math.max(40, ...used.map((l) => label(l).length * 7 + 14)), rail1 = (j) => 8 + LW + 18 + j * 14; + const XA = rail1(Math.max(used.length - 1, 0)) + 50, TIP = XA + 22, rail2 = (t) => TIP + 18 + t * 14; + const XO = rail2(Math.max(terms.length - 1, 0)) + 50, OUT = XO + 20; + const W = OUT + 30 + Math.max(...outputs.map((o) => (o.name || 'ƒ').length * 8)) + 12; + let wires = '', parts = ''; + const path = (sig, d) => ``; + const dot = (sig, x, y) => ``; + const constant = (x, y, text) => `${text}`; + // A rail joins an entry to its taps; a dot marks each point that is not an end of the rail. + const rail = (sig, x, entry, taps) => { + const ys = [entry, ...taps], lo = Math.min(...ys), hi = Math.max(...ys); + wires += path(sig, `M${x} ${lo} V${hi}`); + for (const y of new Set(ys)) if (y > lo && y < hi) wires += dot(sig, x, y); + }; + const pins = (count, y) => Array.from({ length: count }, (_, i) => y + (i - (count - 1) / 2) * PIN); + + used.forEach((lit, j) => { + const sig = `l:${lit}`, taps = []; + terms.forEach((t, ti) => { + const at = t.lits.indexOf(lit); + if (at < 0) return; + const y = t.lits.length === 1 ? ty[ti] : pins(t.lits.length, ty[ti])[at]; + taps.push(y); + wires += path(sig, `M${rail1(j)} ${y} H${t.lits.length === 1 ? TIP : XA - 20}`); + }); + wires += path(sig, `M${8 + LW} ${ly[j]} H${rail1(j)}`); + rail(sig, rail1(j), ly[j], taps); + parts += `` + + `${escapeHtml(label(lit))}`; + }); + terms.forEach((t, ti) => { + const y = ty[ti], hh = gap(t.lits.length) / 2 - 6, sig = `t:${ti}`; + if (t.lits.length === 0) parts += constant(XA, y, '1'); + else if (t.lits.length > 1) parts += ``; + const taps = []; + outputs.forEach((_, k) => { + const at = ofOutput[k].indexOf(t); + if (at < 0) return; + const single = ofOutput[k].length === 1, py = single ? oy[k] : pins(ofOutput[k].length, oy[k])[at]; + taps.push(py); + wires += path(sig, `M${rail2(ti)} ${py} H${single ? OUT : XO - 16}`); + }); + wires += path(sig, `M${t.lits.length === 0 ? XA + 14 : TIP} ${y} H${rail2(ti)}`); + rail(sig, rail2(ti), y, taps); + }); + outputs.forEach((o, k) => { + const y = oy[k], m = ofOutput[k].length, hh = gap(m) / 2 - 6, sig = `o:${k}`; + if (m === 0) parts += constant(XO, y, '0') + path(sig, `M${XO + 14} ${y} H${OUT}`); + else if (m > 1) parts += ``; + parts += path(sig, `M${OUT} ${y} H${OUT + 16}`) + dot(sig, OUT + 16, y) + + `${escapeHtml(o.name || 'ƒ')}`; + }); + box.innerHTML = `${wires}${parts}`; + + // A click or Enter on an input box switches that input. + const svg = box.firstElementChild; + const toggle = (e) => { + const lit = e.target.closest('[data-lit]')?.dataset.lit; + if (!lit || (e.type === 'keydown' && e.key !== 'Enter' && e.key !== ' ')) return; + e.preventDefault(); + onToggle(Number(lit.split(':')[0])); + }; + svg.addEventListener('click', toggle); + svg.addEventListener('keydown', toggle); + + // Paints the circuit for the inputs' values: a literal that holds gets a bold outline, a wire or + // gate carrying 1 is lit, and an output that is 1 is bold. Returns the outputs' values. + return (values) => { + const on = new Set(used.filter((lit) => { const [i, v] = lit.split(':').map(Number); return values[i] === (v === 1); }).map((lit) => `l:${lit}`)); + terms.forEach((t, ti) => { if (t.lits.every((lit) => on.has(`l:${lit}`))) on.add(`t:${ti}`); }); + outputs.forEach((_, k) => { if (ofOutput[k].some((t) => on.has(`t:${terms.indexOf(t)}`))) on.add(`o:${k}`); }); + for (const el of svg.querySelectorAll('[data-sig]')) el.classList.toggle('on', on.has(el.dataset.sig)); + for (const el of svg.querySelectorAll('[data-lit]')) { + el.classList.toggle('on', on.has(`l:${el.dataset.lit}`)); + el.setAttribute('aria-pressed', String(on.has(`l:${el.dataset.lit}`))); + } + return outputs.map((_, k) => on.has(`o:${k}`)); + }; +} + +// ---------------------------------------------------------------- Venn diagram + +function venn(canvas, vars, rows) { + const [w, h] = fitCanvas(canvas, 2); + const ctx = canvas.getContext('2d'), s = w / canvas.clientWidth; + const r = Math.min(w, h) * 0.27, cx = w / 2, cy = h / 2 + r * 0.08; + const circles = vars.length === 1 ? [[cx, cy]] + : vars.length === 2 ? [[cx - r * 0.55, cy], [cx + r * 0.55, cy]] + : [[cx - r * 0.55, cy - r * 0.35], [cx + r * 0.55, cy - r * 0.35], [cx, cy + r * 0.6]]; + const img = ctx.createImageData(w, h), fill = token('--plot-1'), bg = token('--surface'); + const parse = (c) => { const p = document.createElement('span'); p.style.color = c; document.body.append(p); const m = getComputedStyle(p).color.match(/[\d.]+/g).map(Number); p.remove(); return m; }; + const on = parse(fill), off = parse(bg); + for (let y = 0; y < h; y++) + for (let x = 0; x < w; x++) { + let index = 0; + circles.forEach(([px, py], i) => { if ((x - px) ** 2 + (y - py) ** 2 <= r * r) index |= 1 << (vars.length - 1 - i); }); + const lit = rows[index][vars.length]; + const c = lit ? on : off, k = (y * w + x) * 4; + img.data[k] = lit ? c[0] * 0.45 + off[0] * 0.55 : c[0]; + img.data[k + 1] = lit ? c[1] * 0.45 + off[1] * 0.55 : c[1]; + img.data[k + 2] = lit ? c[2] * 0.45 + off[2] * 0.55 : c[2]; + img.data[k + 3] = 255; + } + ctx.putImageData(img, 0, 0); + ctx.strokeStyle = token('--rule'); + ctx.lineWidth = 1.5 * s; + ctx.strokeRect(0.5 * s, 0.5 * s, w - s, h - s); + ctx.strokeStyle = token('--ink'); + ctx.lineWidth = 2 * s; + ctx.fillStyle = token('--ink'); + ctx.font = `italic ${18 * s}px ${token('--font-display')}`; + const labels = [[-1.05, -0.95], [1.05, -0.95], [0, 1.25]]; + circles.forEach(([px, py], i) => { + ctx.beginPath(); ctx.arc(px, py, r, 0, Math.PI * 2); ctx.stroke(); + const [lx, ly] = vars.length === 1 ? [0, -1.2] : labels[i]; + ctx.fillText(vars[i], px + lx * r * 0.85 - 6 * s, py + ly * r * 0.85 + 6 * s); + }); +} diff --git a/live/wwwroot/views/matrices.js b/live/wwwroot/views/matrices.js new file mode 100644 index 0000000000..cda5d75ce6 --- /dev/null +++ b/live/wwwroot/views/matrices.js @@ -0,0 +1,315 @@ +import { $, html, escapeHtml, setChip, presets, tex, token, debounce, fitCanvas } from '../shared.js'; + +// As the Motion tab's double pendulum writes it, so that its link lands on this preset. +const MASS = '[[l_1 ^ 2 * (m_1 + m_2), m_2 * l_1 * l_2 * cos(a_1 - a_2)], [m_2 * l_1 * l_2 * cos(a_1 - a_2), l_2 ^ 2 * m_2]]'; +const MASS_NOTE = 'The mass matrix of the double pendulum in the Motion tab. Its determinant stays positive, since m₂cos² < m₁ + m₂, so the equations can always be solved for the accelerations.'; + +const PRESETS = [ + { label: 'Stretch', a: '[[2, 1], [1, 3]]', + note: 'Symmetric, so its eigenvectors are at right angles. The unit square goes to a parallelogram of area det A = 5.' }, + { label: 'Shear', a: '[[1, 1], [0, 1]]', + note: 'The eigenvalue 1 twice, but only one line of eigenvectors: a shear has no second direction it leaves alone.' }, + { label: 'Rotation', a: '[[cos(t), -sin(t)], [sin(t), cos(t)]]', + note: 'Determinant 1 and inverse equal to its transpose. Its eigenvalues are cos t ± i sin t, complex unless t is a multiple of π.' }, + { label: 'Fibonacci', a: '[[1, 1], [1, 0]]', power: 10, + note: 'Its powers hold the Fibonacci numbers, and its larger eigenvalue is the golden ratio.' }, + { label: 'Singular', a: '[[1, 2, 3], [4, 5, 6], [7, 8, 9]]', + note: 'Rank 2, determinant 0, no inverse: the eigenvalue 0 has the eigenvector (1, −2, 1), which A sends to zero.' }, + { label: 'Symmetric 3 × 3', a: '[[2, 1, 0], [1, 2, 1], [0, 1, 2]]', note: 'Eigenvalues 2 and 2 ± √2, with eigenvectors at right angles.' }, + { label: 'Any 2 × 2', a: '[[a, b], [c, d]]', note: 'The formulas of the 2 × 2 case, all at once.' }, + { label: 'Pauli X and Z', a: '[[0, 1], [1, 0]]', b: '[[1, 0], [0, -1]]', + note: 'XZ = −ZX, and X ⊗ Z acts on two qubits: X on the first, Z on the second.' }, + { label: 'Polar Jacobian', a: 'jacobian([r cos(t), r sin(t)], [r, t])', + note: 'The derivative of (r, t) ↦ (r cos t, r sin t). Its determinant r is the r in dA = r dr dt.' }, + { label: 'A Hessian', a: 'hessian(x^3 - 3 x y^2, [x, y])', + note: 'The monkey saddle. Trace 0 everywhere, since the function is harmonic, and determinant −36(x² + y²), never positive.' }, + { label: 'Double pendulum', a: MASS, note: MASS_NOTE }, +]; + +const MARKUP = ` +
+
+
+

Exact linear algebra

+

Matrices

+
+

Write a matrix row by row, as AngouriMath reads it: [[1, 2], [3, 4]]. Entries can be numbers or formulas, and jacobian(…) and hessian(…) make one. Everything below is computed by AngouriMath, exactly.

+
+
+
+

+
Waiting for AngouriMath
+

+
+
+

A

+

Determinant and trace

+
det A
+
tr A, the sum of the diagonal
+
+

Inverse

+

Transpose

+

Reduced row echelon form

+
+

Powers

+
+ + +
+
+

+
+
+

Eigenvalues and eigenvectors

+
Characteristic polynomial det(A − λI), whose roots are the eigenvalues
+
+

+
+
+

What A does to the plane

+ +
+ + +
+

+
+
+

With B

+
B
+
The product A B

+
The tensor (Kronecker) product A ⊗ B
+

+
+
+
`; + +export function mount(section, am) { + section.classList.add('doc'); + html(section, MARKUP); + const aIn = $(section, '#mat-a'), bIn = $(section, '#mat-b'), chip = $(section, '[data-chip]'), note = $(section, '[data-note]'); + const powerIn = $(section, '#mat-power'), morphIn = $(section, '#mat-morph'), canvas = $(section, '[data-picture]'); + let picture = null; + + const press = presets($(section, '.presets'), PRESETS, (p) => pick(p)); + function pick(p) { + aIn.value = p.a; + bIn.value = p.b ?? ''; + powerIn.value = p.power ?? 2; + note.textContent = p.note ?? ''; + press(p.label); + analyze(); + } + + let generation = 0; + async function analyze() { + const mine = ++generation, t0 = performance.now(); + setChip(chip, '', 'Working'); + let r; + try { + r = await am.json('MatricesJs', 'Analyze', [aIn.value, bIn.value], { timeout: 30000 }); + } catch (e) { + if (mine === generation) { setChip(chip, 'bad', 'AngouriMath stopped'); $(section, '[data-error]').textContent = e.message; } + return; + } + if (mine !== generation) return; + $(section, '[data-timing]').textContent = `${Math.round(performance.now() - t0)} ms`; + if (!r.ok) { + setChip(chip, 'warn', 'Not a matrix yet'); + $(section, '[data-error]').textContent = r.error; + return; + } + $(section, '[data-error]').textContent = ''; + const square = r.rows === r.cols; + setChip(chip, 'ok', `${r.rows} × ${r.cols}${r.numeric ? '' : ', with letters'}`); + for (const card of section.querySelectorAll('[data-square]')) card.hidden = !square; + + tex($(section, '[data-a]'), r.latex); + $(section, '[data-shape]').textContent = `${r.rows} rows, ${r.cols} columns${r.rank !== undefined ? `, rank ${r.rank}` : ''}${r.numeric ? '' : ' (for letters in general position)'}.`; + tex($(section, '[data-transpose]'), r.transpose); + tex($(section, '[data-rref]'), r.rref || ''); + const rrefConditions = $(section, '[data-rref-conditions]'); + rrefConditions.hidden = !r.rref || !r.rrefConditions.length; + tex(rrefConditions, r.rrefConditions.join(',\\quad '), false); + $(section, '[data-rref-note]').textContent = r.numeric + ? 'Row operations until each row starts with a 1 that is alone in its column; the rows left are a basis of the row space.' + : 'Row operations until each row starts with a 1 that is alone in its column, for the letters in general position: a pivot that is a formula is divided by, as if it were not zero.' + + (r.rrefConditions.length ? ' AngouriMath states the form provided:' : ''); + + if (square) { + tex($(section, '[data-det]'), r.det); + tex($(section, '[data-trace]'), r.trace); + tex($(section, '[data-inverse]'), r.inverse || '\\text{none}'); + const conditions = $(section, '[data-inverse-conditions]'); + conditions.hidden = !r.inverse || !r.inverseConditions.length; + tex(conditions, r.inverseConditions.join(',\\quad '), false); + $(section, '[data-inverse-note]').textContent = !r.inverse + ? 'The determinant is 0, so A has no inverse.' + : r.inverseConditions.length + ? 'AngouriMath states the inverse provided:' + : r.numeric ? 'A A⁻¹ = I.' : 'A A⁻¹ = I wherever det A ≠ 0: the adjugate over the determinant.'; + tex($(section, '[data-charpoly]'), r.charpoly ? `${r.charpoly} = 0` : ''); + showEigen(r); + power(); + } + + const pictured = r.entries && r.entries.every(Number.isFinite); + $(section, '[data-picture-card]').hidden = !pictured; + picture = pictured ? { m: r.entries, eigen: r.eigen ?? [], det: r.det } : null; + if (pictured) draw(); + + const bCard = $(section, '[data-b-card]'); + bCard.hidden = !bIn.value.trim(); + $(section, '[data-b-error]').textContent = r.bError ?? ''; + tex($(section, '[data-b]'), r.b ?? ''); + tex($(section, '[data-product]'), r.product ?? ''); + $(section, '[data-product-note]').textContent = r.productNote ?? ''; + tex($(section, '[data-tensor]'), r.tensor ?? ''); + } + + function showEigen(r) { + const box = $(section, '[data-eigen]'), foot = $(section, '[data-eigen-note]'); + box.replaceChildren(); + if (!r.eigen) { + foot.textContent = r.charpoly ? 'AngouriMath gives the polynomial; its roots are shown for matrices of numbers, and with letters up to 2 × 2.' : ''; + return; + } + for (const e of r.eigen) { + const row = document.createElement('div'); + row.className = 'eigen-row'; + // The value beside the exact root only where it says something: 1.381966 beside (5 − √5)/2. + const approx = (e.approx ?? '').replace('i', '\\,\\mathrm{i}'); + const value = e.latex + ? `\\lambda = ${e.latex}${e.approx?.includes('.') ? ` \\approx ${approx}` : ''}` + : `\\lambda \\approx ${approx}`; + const vectors = (e.vectors ?? []).map((v) => v.latex || (v.numeric ? `\\begin{bmatrix}${v.numeric.map((x) => +x.toFixed(5)).join(' \\\\ ')}\\end{bmatrix}` : '')).filter(Boolean); + row.innerHTML = '
'; + tex(row.children[0], value); + row.children[1].hidden = !vectors.length; + tex(row.children[1], vectors.length ? `v = ${vectors.join(',\\; ')}` : ''); + box.append(row); + } + // Every eigenvalue has a vector, yet fewer than n of them: a matrix like the shear. + const counted = r.eigen.reduce((n, e) => n + (e.vectors?.length ?? 0), 0); + const short = r.numeric && counted < r.rows && r.eigen.every((e) => e.vectors?.length); + foot.textContent = !r.numeric + ? 'Eigenvectors are found for matrices of numbers.' + : `The eigenvectors of λ span the null space of A − λI, read off its reduced row echelon form${r.eigen.some((e) => e.latex === '') ? '; a root that needs cube roots is used by its value, so its vectors are decimals' : ''}.` + + (short ? ` Only ${counted} independent eigenvector${counted === 1 ? '' : 's'} for a ${r.rows} × ${r.rows} matrix, so it cannot be diagonalised.` : ''); + } + + async function power() { + $(section, '[data-power-out]').textContent = powerIn.value; + const err = $(section, '[data-power-error]'); + let r; + try { r = await am.json('MatricesJs', 'Power', [+powerIn.value]); } catch (e) { err.textContent = e.message; return; } + if (!r.ok) { err.textContent = r.error; tex($(section, '[data-power]'), ''); return; } + err.textContent = ''; + tex($(section, '[data-power]'), `A^{${powerIn.value}} = ${r.latex}`); + } + + // The plane carried by M(s) = (1 - s) I + s A: the grid, the unit square and the images of + // the two unit vectors, with A's real eigenvector lines, along which A only stretches. + function draw() { + if (!picture || canvas.offsetParent === null) return; + const [w, h] = fitCanvas(canvas, 2); + const ctx = canvas.getContext('2d'), k = w / canvas.clientWidth; + const s = +morphIn.value / 100, [a, b, c, d] = picture.m; + const M = [1 - s + s * a, s * b, s * c, 1 - s + s * d]; + $(section, '[data-morph-out]').textContent = s === 1 ? 'A' : s.toFixed(2); + const reach = Math.max(1.6, ...[[a, c], [b, d], [a + b, c + d]].map(([x, y]) => Math.hypot(x, y))) * 1.25; + const unit = Math.min(w, h) / 2 / reach, cx = w / 2, cy = h / 2; + const P = (x, y) => [cx + (M[0] * x + M[1] * y) * unit, cy - (M[2] * x + M[3] * y) * unit]; + ctx.fillStyle = token('--surface'); + ctx.fillRect(0, 0, w, h); + + // The grid as A carries it. + ctx.lineWidth = k; + ctx.strokeStyle = token('--rule'); + const n = Math.ceil(reach * 3); + for (let i = -n; i <= n; i++) { + for (const [p, q] of [[P(i, -n), P(i, n)], [P(-n, i), P(n, i)]]) { + ctx.beginPath(); ctx.moveTo(...p); ctx.lineTo(...q); ctx.stroke(); + } + } + // The axes as they were. + ctx.strokeStyle = token('--ink-soft'); + ctx.beginPath(); ctx.moveTo(0, cy); ctx.lineTo(w, cy); ctx.moveTo(cx, 0); ctx.lineTo(cx, h); ctx.stroke(); + + // The unit square and its image; a negative determinant turns it over. + const det = M[0] * M[3] - M[1] * M[2]; + ctx.setLineDash([4 * k, 4 * k]); + ctx.strokeStyle = token('--ink-soft'); + ctx.strokeRect(cx, cy - unit, unit, unit); + ctx.setLineDash([]); + const corners = [P(0, 0), P(1, 0), P(1, 1), P(0, 1)]; + ctx.beginPath(); + corners.forEach((p, i) => (i ? ctx.lineTo(...p) : ctx.moveTo(...p))); + ctx.closePath(); + ctx.globalAlpha = 0.22; + ctx.fillStyle = token(det < 0 ? '--plot-2' : '--plot-1'); + ctx.fill(); + ctx.globalAlpha = 1; + + // Eigenvector lines of A. + if (s === 1) + for (const e of picture.eigen) + for (const v of e.vectors ?? []) { + if (!v.numeric) continue; + const [x, y] = v.numeric, len = Math.hypot(x, y); + if (!len) continue; + const ux = x / len, uy = y / len, far = reach * 4 * unit; + ctx.strokeStyle = token('--plot-3'); + ctx.lineWidth = 1.6 * k; + ctx.setLineDash([7 * k, 5 * k]); + ctx.beginPath(); ctx.moveTo(cx - ux * far, cy + uy * far); ctx.lineTo(cx + ux * far, cy - uy * far); ctx.stroke(); + ctx.setLineDash([]); + ctx.fillStyle = token('--plot-3'); + ctx.font = `${12 * k}px ${token('--font-body')}`; + const lx = cx + ux * unit * reach * 0.82, ly = cy - uy * unit * reach * 0.82; + ctx.fillText(`λ = ${e.approx}`, lx + 6 * k, ly - 6 * k); + } + + // A e1 and A e2. + const arrow = (to, color, label) => { + const [x, y] = to, ang = Math.atan2(y - cy, x - cx), head = 10 * k; + ctx.strokeStyle = ctx.fillStyle = token(color); + ctx.lineWidth = 2.4 * k; + ctx.beginPath(); ctx.moveTo(cx, cy); ctx.lineTo(x, y); ctx.stroke(); + ctx.beginPath(); + ctx.moveTo(x, y); + ctx.lineTo(x - head * Math.cos(ang - 0.4), y - head * Math.sin(ang - 0.4)); + ctx.lineTo(x - head * Math.cos(ang + 0.4), y - head * Math.sin(ang + 0.4)); + ctx.closePath(); ctx.fill(); + ctx.font = `600 ${12 * k}px ${token('--font-body')}`; + ctx.fillText(label, x + 6 * k, y - 6 * k); + }; + arrow(P(1, 0), '--plot-1', s === 1 ? 'A e₁' : 'e₁'); + arrow(P(0, 1), '--plot-2', s === 1 ? 'A e₂' : 'e₂'); + + $(section, '[data-picture-note]').textContent = `The shaded square has area |det| = ${+Math.abs(det).toFixed(4)}${det < 0 ? ', turned over, since the determinant is negative' : ''}. ` + + (s === 1 && picture.eigen.some((e) => e.vectors?.some((v) => v.numeric)) + ? 'On the dashed eigenvector lines A only stretches, by λ.' + : s === 1 ? 'A has no real eigenvectors: no line through the origin stays where it is.' : 'Slide to the end to see A itself.'); + } + + // The Motion tab links here with its mass matrix: #matrices?a=... + function fromLink() { + const query = new URLSearchParams(location.hash.split('?')[1] ?? ''); + const a = query.get('a'); + if (!a) return false; + history.replaceState(null, '', '#matrices'); + pick(a === MASS ? PRESETS[PRESETS.length - 1] : { label: null, a, note: MASS_NOTE }); + return true; + } + + const later = debounce(analyze, 500); + aIn.addEventListener('input', () => { press(null); note.textContent = ''; later(); }); + bIn.addEventListener('input', later); + powerIn.addEventListener('input', debounce(power, 150)); + morphIn.addEventListener('input', draw); + new ResizeObserver(draw).observe(canvas); + + if (!fromLink()) pick(PRESETS[0]); + return { show() { fromLink(); draw(); }, hide() {}, restarted: () => analyze() }; +} diff --git a/live/wwwroot/views/motion.js b/live/wwwroot/views/motion.js new file mode 100644 index 0000000000..6d91c9c6fa --- /dev/null +++ b/live/wwwroot/views/motion.js @@ -0,0 +1,324 @@ +import { $, html, setChip, presets, collapsible, tex, token, debounce, linkProgram, fullscreenTriangle, FULLSCREEN_VS, fitCanvas, loop, rgb } from '../shared.js'; + +const sin = Math.sin, cos = Math.cos; +const PENDULUM = { + coords: ['a'], rates: ['w'], kinds: ['angle'], params: { m: 1, l: 1, g: 9.81 }, size: 1.1, + starts: [[1.0, 0], [2.0, 0], [2.9, 0]], + bobs: (s, P) => [[P.l * sin(s[0]), -P.l * cos(s[0])]], + vars: 'a is the angle from straight down and w its rate; m, l and g are 1 kg, 1 m and 9.81 m/s².', +}; +const SYSTEMS = [ + { label: 'Pendulum', lagrangian: 'm l^2 w^2 / 2 + m g l cos(a)', ...PENDULUM, + note: 'Three swings of different size. Bigger swings take longer: the period is not constant, and the phase portrait shows why.' }, + { label: 'Double pendulum', lagrangian: '(m_1 + m_2)/2 l_1^2 w_1^2 + m_2/2 l_2^2 w_2^2 + m_2 l_1 l_2 w_1 w_2 cos(a_1 - a_2) + (m_1 + m_2) g l_1 cos(a_1) + m_2 g l_2 cos(a_2)', + coords: ['a_1', 'a_2'], rates: ['w_1', 'w_2'], kinds: ['angle', 'angle'], params: { m_1: 1, m_2: 1, l_1: 1, l_2: 1, g: 9.81 }, size: 2.15, + starts: [[2.0, 2.5, 0, 0], [2.000001, 2.5, 0, 0], [2.000002, 2.5, 0, 0]], + bobs: (s, P) => { const p1 = [P.l_1 * sin(s[0]), -P.l_1 * cos(s[0])]; return [p1, [p1[0] + P.l_2 * sin(s[1]), p1[1] - P.l_2 * cos(s[1])]]; }, + vars: 'a_1 and a_2 are the angles of the two arms, w_1 and w_2 their rates. Names carry an underscore because AngouriMath reads m1 as m to the power 1.', + note: 'Three copies started a millionth of a radian apart. They agree for a few seconds, then go their own ways: chaos.' }, + { label: 'Spring pendulum', lagrangian: 'm/2 (v^2 + r^2 w^2) + m g r cos(a) - k/2 (r - l_0)^2', + coords: ['r', 'a'], rates: ['v', 'w'], kinds: ['length', 'angle'], params: { m: 1, g: 9.81, k: 40, l_0: 1 }, size: 2.0, spring: true, + starts: [[1.3, 1.0, 0, 0]], + bobs: (s) => [[s[0] * sin(s[1]), -s[0] * cos(s[1])]], + vars: 'r is the spring’s length and v its rate, a the angle and w its rate; k is 40 N/m and the spring’s rest length l_0 is 1 m.', + note: 'Stretching and swinging trade energy back and forth.' }, + { label: 'A typo', lagrangian: 'm l w^2 / 2 + m g l cos(a)', ...PENDULUM, + note: 'The kinetic energy lost a length. The units check stops it before any motion is computed.' }, +]; + +const MARKUP = ` + +
+ + +

+
+`; + +const PHASE_FS = (fn) => `#version 300 es +precision highp float; +in vec2 vNdc; +uniform vec2 uHalf; +uniform float uLevel; +uniform vec3 uLo, uHi, uMid, uInk; +out vec4 outColor; +${fn} +void main() { + vec2 p = vNdc * uHalf; + float e = energy(p); + float t = tanh(e / uLevel); + vec3 col = t < 0.0 ? mix(uMid, uLo, -t * 0.7) : mix(uMid, uHi, t * 0.7); + float k = e / uLevel * 3.0; + float line = abs(fract(k + 0.5) - 0.5) / max(fwidth(k), 1e-5); + col = mix(col, uInk, 0.45 * (1.0 - min(line, 1.0))); + outColor = vec4(col, 1.0); +}`; + +export function mount(section, am) { + html(section, MARKUP); + const canvas = $(section, 'canvas'), phase = $(section, '[data-phase]'), dots = $(section, '[data-phase-dots]'); + const chip = $(section, '[data-chip]'); + collapsible($(section, '.panel')); + const pgl = phase.getContext('webgl2', { antialias: false }); + const pvao = pgl && fullscreenTriangle(pgl); + let phaseProg = null; + + let system = SYSTEMS[0], states = [], trails = [], phaseTrails = [], time = 0, e0 = null, ready = false; + let busy = false, playing = !matchMedia('(prefers-reduced-motion: reduce)').matches; + const W_HALF = 9; + + function reset() { + states = system.starts.map((s) => [...s]); + trails = states.map(() => []); + phaseTrails = states.map(() => []); + time = 0; + e0 = null; + $(section, '[data-drift]').textContent = '–'; + } + + async function derive(text) { + ready = false; + setChip(chip, '', 'Deriving'); + const t0 = performance.now(); + let r; + try { + r = await am.json('MotionJs', 'Derive', [text, system.coords, system.rates, system.kinds, Object.keys(system.params), Object.values(system.params)]); + } catch (e) { setChip(chip, 'bad', 'AngouriMath stopped'); $(section, '[data-error]').textContent = e.message; return; } + $(section, '[data-timing]').textContent = `${Math.round(performance.now() - t0)} ms`; + if (!r.ok) { + setChip(chip, 'bad', r.error.startsWith('Could not read') ? 'Not a formula yet' : 'Rejected'); + $(section, '[data-error]').textContent = r.error; + $(section, '[data-units]').textContent = ''; + tex($(section, '[data-equation]'), ''); + tex($(section, '[data-energy]'), ''); + $(section, '[data-mass]').replaceChildren(); + states = []; + return; + } + setChip(chip, 'ok', 'An energy: equations derived'); + $(section, '[data-error]').textContent = ''; + $(section, '[data-units]').textContent = r.units; + tex($(section, '[data-equation]'), r.equation); + tex($(section, '[data-energy]'), `E = ${r.energy}`); + // The matrix on the left, as AngouriMath writes it, can be taken apart in the Matrices tab. + $(section, '[data-mass]').innerHTML = r.mass + ? `The mass matrix in the Matrices tab: its determinant, inverse and eigenvalues.` + : ''; + phaseProg = null; + if (pgl && r.energyGlsl) { + try { phaseProg = linkProgram(pgl, FULLSCREEN_VS, PHASE_FS(r.energyGlsl)); } catch { phaseProg = null; } + } + $(section, '[data-phase-label]').textContent = system.coords.length === 1 + ? `Phase portrait: ${system.coords[0]} across, ${system.rates[0]} up; curves of equal energy, drawn from E on the GPU` + : `Configuration: ${system.coords[0]} across, ${system.coords[1]} up`; + reset(); + ready = true; + } + + // ------------------------------------------------------------ simulation and drawing + const colours = ['--plot-1', '--plot-2', '--plot-3']; + const wrap = (a) => Math.atan2(Math.sin(a), Math.cos(a)); + + async function step(dt) { + if (!ready || busy || !playing || !states.length) return; + busy = true; + const steps = Math.max(1, Math.min(10, Math.round(dt * 240))); + try { + const flat = await am.call('MotionJs', 'Step', [states.flat(), 1 / 240, steps]); + const size = states[0].length; + states = states.map((_, i) => flat.slice(i * size, (i + 1) * size)); + time += steps / 240; + states.forEach((s, i) => { + const end = system.bobs(s, system.params).at(-1); + trails[i].push(end); + if (trails[i].length > 360) trails[i].shift(); + phaseTrails[i].push(system.coords.length === 1 ? [wrap(s[0]), s[1]] : [wrap(s[0]), wrap(s[1])]); + if (phaseTrails[i].length > 900) phaseTrails[i].shift(); + }); + } catch { /* stopped; the chip says so on the next derive */ } + busy = false; + } + + let energyClock = 0; + async function energyCheck() { + if (!ready || !states.length) return; + try { + const es = await am.call('MotionJs', 'Energies', [states.flat()]); + if (e0 === null) { e0 = es; return; } + const drift = Math.max(...es.map((e, i) => Math.abs(e - e0[i]) / Math.max(Math.abs(e0[i]), 1e-9))); + $(section, '[data-drift]').textContent = drift < 1e-12 ? '< 1e-12' : drift.toExponential(1); + } catch { /* ignore */ } + } + + function drawScene() { + const [w, h] = fitCanvas(canvas, 2); + const ctx = canvas.getContext('2d'), s = w / canvas.clientWidth; + ctx.fillStyle = token('--surface'); + ctx.fillRect(0, 0, w, h); + if (!states.length) return; + const wide = canvas.clientWidth > 900; + // The pivot sits mid-height: a pendulum swinging over the top needs as much room above as below. + const ox = wide ? w * 0.6 : w * 0.5, oy = wide ? h * 0.47 : h * 0.3; + const scale = Math.min(w * (wide ? 0.3 : 0.42), h * (wide ? 0.4 : 0.26)) / system.size; + const X = (p) => ox + p[0] * scale, Y = (p) => oy - p[1] * scale; + ctx.fillStyle = token('--ink'); + ctx.fillRect(ox - 40 * s, oy - 3 * s, 80 * s, 3 * s); + states.forEach((st, i) => { + const colour = token(colours[i % colours.length]); + const trail = trails[i]; + ctx.lineWidth = 1.6 * s; + for (let k = 1; k < trail.length; k++) { + ctx.strokeStyle = colour; + ctx.globalAlpha = (k / trail.length) * 0.6; + ctx.beginPath(); ctx.moveTo(X(trail[k - 1]), Y(trail[k - 1])); ctx.lineTo(X(trail[k]), Y(trail[k])); ctx.stroke(); + } + ctx.globalAlpha = 1; + let prev = [0, 0]; + for (const b of system.bobs(st, system.params)) { + ctx.strokeStyle = token('--ink'); + ctx.lineWidth = 2.4 * s; + ctx.beginPath(); + if (system.spring) { + // A zigzag between the pivot and the bob. + const n = 14, dx = b[0] - prev[0], dy = b[1] - prev[1], len = Math.hypot(dx, dy), nx = -dy / len, ny = dx / len; + ctx.moveTo(X(prev), Y(prev)); + for (let k = 1; k < n; k++) { + const t = k / n, o = (k % 2 ? 1 : -1) * 0.06; + ctx.lineTo(X([prev[0] + dx * t + nx * o, 0]), Y([0, prev[1] + dy * t + ny * o])); + } + ctx.lineTo(X(b), Y(b)); + } else { ctx.moveTo(X(prev), Y(prev)); ctx.lineTo(X(b), Y(b)); } + ctx.stroke(); + ctx.fillStyle = colour; + ctx.beginPath(); ctx.arc(X(b), Y(b), 11 * s, 0, Math.PI * 2); ctx.fill(); + ctx.strokeStyle = token('--surface'); + ctx.lineWidth = 2 * s; + ctx.stroke(); + prev = b; + } + }); + ctx.fillStyle = token('--ink'); + ctx.beginPath(); ctx.arc(ox, oy, 4 * s, 0, Math.PI * 2); ctx.fill(); + } + + function drawPhase() { + const [pw, ph] = fitCanvas(phase, 2); + const [dw, dh] = fitCanvas(dots, 2); + const one = system.coords.length === 1; + const hx = Math.PI, hy = one ? W_HALF : Math.PI; + if (pgl) { + pgl.viewport(0, 0, pw, ph); + if (one && phaseProg) { + pgl.useProgram(phaseProg.program); + pgl.uniform2f(phaseProg.loc.uHalf, hx, hy); + const P = system.params; + pgl.uniform1f(phaseProg.loc.uLevel, (P.m ?? 1) * (P.g ?? 9.81) * (P.l ?? 1)); + pgl.uniform3fv(phaseProg.loc.uLo, rgb('--plot-1')); + pgl.uniform3fv(phaseProg.loc.uHi, rgb('--plot-2')); + pgl.uniform3fv(phaseProg.loc.uMid, rgb('--surface')); + pgl.uniform3fv(phaseProg.loc.uInk, rgb('--ink')); + pgl.bindVertexArray(pvao); + pgl.drawArrays(pgl.TRIANGLES, 0, 3); + } else { + pgl.clearColor(...rgb('--surface'), 1); + pgl.clear(pgl.COLOR_BUFFER_BIT); + } + } + const ctx = dots.getContext('2d'), s = dw / dots.clientWidth; + ctx.clearRect(0, 0, dw, dh); + const X = (x) => (x + hx) / (2 * hx) * dw, Y = (y) => dh - (y + hy) / (2 * hy) * dh; + ctx.strokeStyle = token('--rule'); + ctx.lineWidth = s; + ctx.beginPath(); ctx.moveTo(X(0), 0); ctx.lineTo(X(0), dh); ctx.moveTo(0, Y(0)); ctx.lineTo(dw, Y(0)); ctx.stroke(); + phaseTrails.forEach((trail, i) => { + const colour = token(colours[i % colours.length]); + if (!one) { + ctx.strokeStyle = colour; + ctx.globalAlpha = 0.5; + ctx.lineWidth = 1.2 * s; + ctx.beginPath(); + trail.forEach((p, k) => { + const jump = k > 0 && (Math.abs(p[0] - trail[k - 1][0]) > Math.PI || Math.abs(p[1] - trail[k - 1][1]) > Math.PI); + (k === 0 || jump) ? ctx.moveTo(X(p[0]), Y(p[1])) : ctx.lineTo(X(p[0]), Y(p[1])); + }); + ctx.stroke(); + ctx.globalAlpha = 1; + } + const p = trail.at(-1); + if (!p) return; + ctx.fillStyle = colour; + ctx.beginPath(); ctx.arc(X(p[0]), Y(p[1]), 5 * s, 0, Math.PI * 2); ctx.fill(); + ctx.strokeStyle = token('--surface'); + ctx.lineWidth = 1.5 * s; + ctx.stroke(); + }); + } + + const animation = loop((dt) => { + step(dt); + energyClock += dt; + if (energyClock > 0.5) { energyClock = 0; energyCheck(); } + $(section, '[data-time]').textContent = `${time.toFixed(1)} s`; + drawScene(); + drawPhase(); + }); + + // ------------------------------------------------------------ controls + const input = $(section, '#motion-input'), note = $(section, '[data-note]'); + const press = presets($(section, '.presets'), SYSTEMS, (p) => { + system = p; + input.value = p.lagrangian; + note.textContent = p.note || ''; + $(section, '[data-vars]').textContent = p.vars; + press(p.label); + derive(p.lagrangian); + }); + system = SYSTEMS[0]; + input.value = system.lagrangian; + note.textContent = system.note; + $(section, '[data-vars]').textContent = system.vars; + press(system.label); + const later = debounce(() => derive(input.value), 500); + input.addEventListener('input', () => { press(null); note.textContent = ''; later(); }); + const play = $(section, '[data-play]'); + const syncPlay = () => { play.textContent = playing ? 'Pause' : 'Play'; }; + play.addEventListener('click', () => { playing = !playing; syncPlay(); }); + syncPlay(); + $(section, '[data-reset]').addEventListener('click', reset); + + derive(input.value); + return { show: () => animation.start(), hide: () => animation.stop(), restarted: () => derive(input.value) }; +} diff --git a/live/wwwroot/views/numbers.js b/live/wwwroot/views/numbers.js new file mode 100644 index 0000000000..0438948847 --- /dev/null +++ b/live/wwwroot/views/numbers.js @@ -0,0 +1,271 @@ +import { $, html, escapeHtml, setChip, presets, tex, debounce } from '../shared.js'; + +const PRESETS = [ + { label: 'A Mersenne prime', n: '2^89 - 1', + note: 'AngouriMath decides that 2^89 − 1 is prime by the Lucas–Lehmer test; trial division up to its square root would not finish.' }, + { label: '100!', n: '100!', note: 'Integers have no size limit: all 158 digits are exact.' }, + { label: '0.1 + 0.2', n: '0.1 + 0.2', + note: 'Exactly 3/10. In floating point it is 0.30000000000000004, because 0.1 has no finite expansion in base 2, as the table of bases shows.' }, + { label: '1/7', n: '1/7', base: 7, note: 'A fraction stays a fraction. Its decimal repeats every six digits; in base 7 it ends after one.' }, + { label: 'Ramanujan’s constant', n: 'e^(pi sqrt(163))', digits: 40, + note: 'Within 10⁻¹² of a whole number, which takes 30 significant digits to see.' }, + { label: 'Euler’s identity', n: 'e^(i pi)', note: 'e^(iπ) + 1 = 0: AngouriMath evaluates the power exactly, to −1.' }, + { label: 'Euclid', n: '1071', m: '462', note: 'gcd(1071, 462) = 21, the example Euclid’s algorithm is usually shown with.' }, + { label: 'Project Euler 3', n: '600851475143', note: 'Its largest prime factor is 6857.' }, + { label: 'Cole’s number', n: '2^67 - 1', + note: 'Mersenne listed 2^67 − 1 as a prime. In 1903 Frank Nelson Cole showed that it is not by multiplying out its two factors; AngouriMath finds them by Pollard’s rho.' }, + { label: 'A complex quotient', n: '(1 + 2i) / (3 - i)', note: 'Complex fractions stay exact too.' }, + { label: 'A cube root', n: '(1 + i)^(1/3)', note: 'The principal cube root: one third of the angle, the cube root of the length.' }, + { label: 'The Basel problem', n: 'zeta(2)', + note: 'The sum of 1/n² over every whole n. AngouriMath knows the zeta function exactly at the even arguments: π²/6.' }, + { label: 'Apéry’s constant', n: 'zeta(3)', digits: 100, + note: 'ζ(3) has no known closed form, so it stays as written, and is evaluated to the digits asked for.' }, + { label: '√2 to 1000 digits', n: 'sqrt(2)', digits: 1000 }, +]; + +const KINDS = { integer: 'An integer', rational: 'A fraction', real: 'A real number', complex: 'A complex number' }; + +const MARKUP = ` +
+
+
+

Exact arithmetic, primes and bases

+

Numbers

+
+

AngouriMath keeps numbers exact: integers of any size, fractions, roots and π stay what they are, and decimals come out to as many digits as you ask for. Type a number, or a formula of numbers.

+
+
+

+
Waiting for AngouriMath
+

+
+
+

Exact value

+
+

Decimal

+
+ + +
+

+      

+
+
+

Primes and divisors

+
+
+
+

+
+
+

With a second integer

+
+
+
+
+
+

On the complex plane

+
+
+
+
+

In other bases

+
+ + +
+
+

+
+ Read + + in base + + as +
+
+

+
+
+
`; + +export function mount(section, am) { + section.classList.add('doc'); + html(section, MARKUP); + const input = $(section, '#num-input'), other = $(section, '#num-other'), chip = $(section, '[data-chip]'), note = $(section, '[data-note]'); + const digitsIn = $(section, '#num-digits'), baseIn = $(section, '#num-base'); + const fromIn = $(section, '#num-from'), fromBase = $(section, '#num-from-base'); + for (let b = 2; b <= 36; b++) fromBase.add(new Option(String(b), String(b), false, b === 16)); + + const syncLabels = () => { + $(section, '[data-digits-out]').textContent = digitsIn.value; + $(section, '[data-base-out]').textContent = baseIn.value; + }; + + const press = presets($(section, '.presets'), PRESETS, (p) => { + input.value = p.n; + other.value = p.m ?? ''; + digitsIn.value = p.digits ?? 50; + baseIn.value = p.base ?? 3; + note.textContent = p.note ?? ''; + press(p.label); + syncLabels(); + describe(); + }); + + let generation = 0; + async function describe() { + const mine = ++generation, t0 = performance.now(); + setChip(chip, '', 'Working'); + let r; + try { + r = await am.json('NumbersJs', 'Describe', [input.value, +digitsIn.value, +baseIn.value, other.value]); + } catch (e) { + if (mine === generation) { setChip(chip, 'bad', 'AngouriMath stopped'); $(section, '[data-error]').textContent = e.message; } + return; + } + if (mine !== generation) return; + $(section, '[data-timing]').textContent = `${Math.round(performance.now() - t0)} ms`; + if (!r.ok) { + setChip(chip, 'warn', 'Not a number yet'); + $(section, '[data-error]').textContent = r.error; + return; + } + $(section, '[data-error]').textContent = ''; + setChip(chip, 'ok', KINDS[r.kind]); + + tex($(section, '[data-exact]'), r.exactLatex || `\\text{${r.exactText.replace(/[{}\\]/g, '')}}`); + $(section, '[data-exact-note]').textContent = { + integer: `${r.length} digit${r.length === 1 ? '' : 's'}, every one exact.`, + rational: 'A fraction in lowest terms, kept exact.', + real: r.exactText === r.decimal ? 'A decimal.' : 'Kept as AngouriMath simplifies it; the decimal is computed from this.', + complex: 'Real and imaginary parts, each kept exact where it can be.', + }[r.kind]; + + $(section, '[data-decimal]').textContent = r.decimal; + $(section, '[data-decimal-note]').textContent = r.kind === 'rational' + ? (r.period ? `The block in brackets repeats forever, every ${r.period} digit${r.period === 1 ? '' : 's'}: long division of the exact fraction, so the slider does not apply.` : 'The decimal ends: the denominator has no prime but 2 and 5.') + : r.kind === 'integer' ? 'An integer is its own decimal.' + : r.kind === 'complex' && !/\d{12}/.test(r.decimal) ? 'Both parts are fractions, written out exactly.' + : `${digitsIn.value} significant digits, from AngouriMath’s arbitrary-precision evaluation.`; + + showBases(r); + showInteger(r, mine); + showComplex(r); + } + + function showBases(r) { + const card = $(section, '[data-bases-card]'); + card.hidden = !r.bases; + if (!r.bases) return; + $(section, '[data-bases]').innerHTML = r.bases.map((b) => + `base ${b.base}${escapeHtml(b.digits)}${b.exact ? '' : '…'}`).join(''); + $(section, '[data-bases-note]').textContent = r.kind === 'rational' + ? 'A fraction by long division, its repeating block in brackets. AngouriMath’s ToBaseN writes the same digits, exactly, and cuts a block that repeats where the precision ends.' + : r.kind === 'integer' + ? 'Written by AngouriMath’s ToBaseN, exactly, with digits up to Z for base 36.' + : 'Written by AngouriMath’s ToBaseN, with digits up to Z for base 36. An expansion that does not end is cut where the precision ends; … marks the cut.'; + } + + async function showInteger(r, mine) { + const integer = r.kind === 'integer'; + $(section, '[data-prime-card]').hidden = !integer; + $(section, '[data-gcd-card]').hidden = !integer; + if (!integer) return; + const prime = { + yes: 'Yes, decided by Miller–Rabin, which is exact below 3.3 × 10²⁴, or by Lucas–Lehmer for 2^p − 1.', + no: 'No.', + undecided: 'Undecided: it passes Miller–Rabin, but past 3.3 × 10²⁴ passing is not a proof, so AngouriMath does not say yes.', + }[r.prime]; + const facts = $(section, '[data-facts]'); + facts.innerHTML = `
Prime
${prime}
`; + const factors = $(section, '[data-factors]'), divisors = $(section, '[data-divisors]'), foot = $(section, '[data-factor-note]'); + shown(factors, ''); + divisors.replaceChildren(); + foot.textContent = ''; + if (r.other) { + $(section, '[data-gcd]').innerHTML = `
Greatest common divisor
${r.other.gcd}
Least common multiple
${r.other.lcm}
`; + shown($(section, '[data-ratio]'), r.other.ratioLatex); + } else { + $(section, '[data-gcd]').innerHTML = '
Type a second integer for their greatest common divisor, least common multiple and quotient.
'; + shown($(section, '[data-ratio]'), ''); + } + let f; + try { + f = await am.json('NumbersJs', 'Factor', [input.value], { timeout: 15000 }); + } catch (e) { if (mine === generation) foot.textContent = `Not factored. ${e.message}`; return; } + if (mine !== generation) return; + if (!f.ok) { foot.textContent = f.error; return; } + shown(factors, `${r.decimal} = ${f.latex}`); + facts.innerHTML += `
Divisors
${f.divisorCount}
Euler’s φ(n)
${f.totient}, the integers from 1 to n with no factor in common with n
`; + if (f.divisors) divisors.innerHTML = f.divisors.map((d) => `${d}`).join(''); + foot.textContent = `Factorised, counted and φ taken by AngouriMath in ${f.ms} ms.`; + } + + function showComplex(r) { + const card = $(section, '[data-complex-card]'); + card.hidden = !r.complex; + if (!r.complex) return; + const c = r.complex; + const parts = $(section, '[data-parts]'); + parts.innerHTML = ''; + for (const [name, key] of [['Real part', 're'], ['Imaginary part', 'im'], ['Modulus |z|', 'abs'], ['Argument arg z', 'arg']]) { + parts.insertAdjacentHTML('beforeend', `
${name}
`); + tex(parts.lastElementChild, c[key], false); + } + $(section, '[data-plane]').replaceChildren(plane(c.x, c.y)); + } + + async function readBase() { + const err = $(section, '[data-from-error]'); + let r; + try { r = await am.json('NumbersJs', 'FromBase', [fromIn.value, +fromBase.value]); } catch (e) { err.textContent = e.message; return; } + if (!r.ok) { err.textContent = r.error; shown($(section, '[data-from]'), ''); return; } + err.textContent = ''; + shown($(section, '[data-from]'), r.latex, false); + } + + const later = debounce(describe, 450); + input.addEventListener('input', () => { press(null); note.textContent = ''; later(); }); + other.addEventListener('input', later); + digitsIn.addEventListener('input', () => { syncLabels(); later(); }); + baseIn.addEventListener('input', () => { syncLabels(); later(); }); + const laterBase = debounce(readBase, 300); + fromIn.addEventListener('input', laterBase); + fromBase.addEventListener('change', readBase); + + input.value = PRESETS[0].n; + press(PRESETS[0].label); + note.textContent = PRESETS[0].note; + syncLabels(); + describe(); + readBase(); + return { show() {}, hide() {} }; +} + +/** LaTeX that is there only sometimes: hidden while empty, rather than shown as a dash. */ +function shown(el, latex, display = true) { + el.hidden = !latex; + tex(el, latex, display); +} + +/** The point z on the complex plane, with its modulus as a circle and its argument as an arc. */ +function plane(x, y) { + const W = 320, H = 260, r = Math.hypot(x, y) || 1, scale = 100 / r; + const cx = W / 2, cy = H / 2, px = cx + x * scale, py = cy - y * scale; + const soft = 'stroke:var(--ink-soft);stroke-width:1', accent = 'var(--plot-1)'; + const angle = Math.atan2(y, x), arc = 28; + const end = [cx + arc * Math.cos(angle), cy - arc * Math.sin(angle)]; + let svg = ``; + svg += `Re`; + svg += `Im`; + svg += ``; + svg += ``; + svg += ``; + svg += ``; + svg += ``; + svg += `z`; + const box = document.createElement('div'); + box.innerHTML = `${svg}`; + return box.firstElementChild; +} diff --git a/live/wwwroot/views/regions.js b/live/wwwroot/views/regions.js new file mode 100644 index 0000000000..dd7fd939b2 --- /dev/null +++ b/live/wwwroot/views/regions.js @@ -0,0 +1,212 @@ +import { $, html, escapeHtml, setChip, presets, collapsible, tex, token, debounce, linkProgram, fullscreenTriangle, FULLSCREEN_VS, fitCanvas, rgb, codeBlock, CODE_BLOCK } from '../shared.js'; +import { numberLine, niceStep } from './representations.js'; + +const PRESETS = [ + { label: 'Disk and half-plane', formula: 'x^2 + y^2 < 4 and y > x - 1', + note: 'The two boundaries meet where AngouriMath solves the circle and the line together: exactly, with square roots.' }, + { label: 'Lens', formula: 'y > x^2 - 2 and y < 2 - x^2' }, + { label: 'Ring', formula: 'x^2 + y^2 > 1 and x^2 + y^2 < 4' }, + { label: 'Hyperbolas', formula: 'x y > 1 or x y < -1' }, + { label: 'Under a wave', formula: 'y < sin(x) + x / 3 and y > -2', + note: 'The boundary is drawn exactly by its gradient, though AngouriMath cannot solve sin(x) + x/3 = -2 for x.' }, + { label: 'On the line: x³ − x > 0', formula: 'x^3 - x > 0', note: 'With only x, the answer is a set of numbers.' }, + { label: 'On the line: a set', formula: '[1; 3) \\/ (2; 5] \\/ {7}', note: 'Intervals and points; AngouriMath merges the overlap.' }, +]; + +const MARKUP = ` + + +`; + +const FS = (fns, edgeCount) => `#version 300 es +precision highp float; +in vec2 vNdc; +uniform vec2 uCenter, uHalf; +uniform float uPixel, uStep; +uniform vec3 uBg, uFill, uInk, uRule, uEdge; +out vec4 outColor; +${fns} +void main() { + vec2 p = uCenter + vNdc * uHalf; + vec3 col = regionInside(p) ? mix(uBg, uFill, 0.32) : uBg; + vec2 g = abs(fract(p / uStep + 0.5) - 0.5) * uStep / uPixel; + col = mix(col, uRule, 0.55 * (1.0 - smoothstep(0.0, 1.0, min(g.x, g.y)))); + vec2 a = abs(p) / uPixel; + col = mix(col, uInk, 0.5 * (1.0 - smoothstep(0.5, 1.5, min(a.x, a.y)))); + float lines = 0.0; + ${Array.from({ length: edgeCount }, (_, i) => `{ + vec3 r = edge${i}(p); + // |g| / |grad g| is the distance to the curve g = 0, to first order: exact-width lines. + float d = abs(r.x) / max(length(r.yz), 1e-6) / uPixel; + lines = max(lines, 1.0 - smoothstep(0.8, 2.0, d)); + }`).join('\n ')} + col = mix(col, uEdge, lines); + outColor = vec4(col, 1.0); +}`; + +export function mount(section, am) { + html(section, MARKUP); + const [canvas, overlay] = section.querySelectorAll('canvas'); + const chip = $(section, '[data-chip]'); + collapsible($(section, '.panel')); + const setCode = codeBlock($(section, '[data-code]')); + const gl = canvas.getContext('webgl2', { antialias: false }); + const vao = gl && fullscreenTriangle(gl); + let prog = null, points = [], dims = 2; + const view = { cx: 0, cy: 0, half: 3.2 }; + + function draw() { + const [w, h] = fitCanvas(canvas, 1.75); + const [ow, oh] = fitCanvas(overlay, 1.75); + const ctx = overlay.getContext('2d'); + ctx.clearRect(0, 0, ow, oh); + if (!gl) return; + gl.viewport(0, 0, w, h); + if (dims !== 2 || !prog) { gl.clearColor(...rgb('--surface'), 1); gl.clear(gl.COLOR_BUFFER_BIT); return; } + const aspect = w / h, hx = aspect >= 1 ? view.half * aspect : view.half, hy = aspect >= 1 ? view.half : view.half / aspect; + const pixel = 2 * hx / w, step = niceStep(hy / 4); + // With the panel on the left, the origin sits in the middle of the uncovered part. + const cx = view.cx - hx * (canvas.clientWidth > 900 ? 450 / canvas.clientWidth : 0), cy = view.cy; + gl.useProgram(prog.program); + gl.uniform2f(prog.loc.uCenter, cx, cy); + gl.uniform2f(prog.loc.uHalf, hx, hy); + gl.uniform1f(prog.loc.uPixel, pixel); + gl.uniform1f(prog.loc.uStep, step); + gl.uniform3fv(prog.loc.uBg, rgb('--surface')); + gl.uniform3fv(prog.loc.uFill, rgb('--plot-1')); + gl.uniform3fv(prog.loc.uInk, rgb('--ink')); + gl.uniform3fv(prog.loc.uRule, rgb('--rule')); + gl.uniform3fv(prog.loc.uEdge, rgb('--plot-2')); + gl.bindVertexArray(vao); + gl.drawArrays(gl.TRIANGLES, 0, 3); + // Labels and the exact crossing points, on a 2D canvas above. + const s = ow / overlay.clientWidth; + const X = (x) => (x - cx + hx) / (2 * hx) * ow, Y = (y) => oh - (y - cy + hy) / (2 * hy) * oh; + ctx.font = `${11 * s}px ${token('--font-body')}`; + ctx.fillStyle = token('--ink-soft'); + for (let x = Math.ceil((cx - hx) / step) * step; x <= cx + hx; x += step) + if (Math.abs(x) > step / 2) ctx.fillText(+x.toFixed(6) + '', X(x) + 3 * s, Math.min(Math.max(Y(0) + 13 * s, 13 * s), oh - 4 * s)); + for (let y = Math.ceil((cy - hy) / step) * step; y <= cy + hy; y += step) + if (Math.abs(y) > step / 2) ctx.fillText(+y.toFixed(6) + '', Math.min(Math.max(X(0) + 4 * s, 4 * s), ow - 40 * s), Y(y) - 3 * s); + for (const p of points) { + ctx.beginPath(); + ctx.arc(X(p.x), Y(p.y), 5 * s, 0, Math.PI * 2); + ctx.fillStyle = token('--surface'); + ctx.fill(); + ctx.lineWidth = 2.2 * s; + ctx.strokeStyle = token('--ink'); + ctx.stroke(); + } + } + + let generation = 0; + async function analyze(text) { + const mine = ++generation, t0 = performance.now(); + setChip(chip, '', 'Working'); + let r; + try { + r = await am.json('RegionsJs', 'Analyze', [text]); + } catch (e) { + if (mine === generation) { setChip(chip, 'bad', 'AngouriMath stopped'); $(section, '[data-error]').textContent = e.message; } + return; + } + if (mine !== generation) return; + $(section, '[data-timing]').textContent = `${Math.round(performance.now() - t0)} ms`; + if (!r.ok) { setChip(chip, 'warn', 'Nothing to draw yet'); $(section, '[data-error]').textContent = r.error; return; } + $(section, '[data-error]').textContent = ''; + dims = r.dims; + $(section, '[data-plane]').hidden = dims !== 2; + $(section, '[data-line]').hidden = dims !== 1; + $(section, '[data-code]').hidden = dims !== 2; + if (dims === 1) { + setChip(chip, 'ok', 'A set of numbers'); + $(section, '[data-how]').textContent = `AngouriMath, ${r.how}`; + tex($(section, '[data-set]'), r.setLatex); + $(section, '[data-numberline]').replaceChildren(r.intervals ? numberLine(r.intervals) : document.createTextNode(r.set)); + points = []; + draw(); + return; + } + try { + const next = linkProgram(gl, FULLSCREEN_VS, FS(r.glsl, r.edges.length)); + if (prog) gl.deleteProgram(prog.program); + prog = next; + } catch (e) { + setChip(chip, 'bad', 'The GPU did not accept the shader'); + $(section, '[data-error]').textContent = e.message; + return; + } + setChip(chip, 'ok', 'Region drawn on the GPU'); + tex($(section, '[data-solved]'), r.solvedYLatex || '\\text{not solved}'); + $(section, '[data-edges]').replaceChildren(...r.edges.map((e) => { const d = document.createElement('div'); d.className = 'tex'; tex(d, e.latex); return d; })); + points = r.points; + $(section, '[data-points]').innerHTML = r.points.length + ? r.points.map((p) => `
${escapeHtml(p.text)} ≈ (${p.x.toPrecision(5)}, ${p.y.toPrecision(5)})
`).join('') + : '

None found.

'; + setCode(r.glsl, '', 'regionInside() is the statement itself; each edgeN() returns g, ∂g/∂x and ∂g/∂y for one boundary g = 0.'); + draw(); + } + + const input = $(section, '#regions-input'), note = $(section, '[data-note]'); + const press = presets($(section, '.presets'), PRESETS, (p) => { + input.value = p.formula; + note.textContent = p.note || ''; + press(p.label); + view.cx = 0; view.cy = 0; view.half = 3.2; + analyze(p.formula); + }); + input.value = PRESETS[0].formula; + note.textContent = PRESETS[0].note; + press(PRESETS[0].label); + const later = debounce(() => analyze(input.value), 450); + input.addEventListener('input', () => { press(null); note.textContent = ''; later(); }); + + let drag = null; + canvas.addEventListener('pointerdown', (e) => { drag = { x: e.clientX, y: e.clientY }; canvas.setPointerCapture(e.pointerId); }); + canvas.addEventListener('pointermove', (e) => { + if (!drag) return; + const k = 2 * view.half / Math.min(canvas.clientWidth, canvas.clientHeight); + view.cx -= (e.clientX - drag.x) * k; + view.cy += (e.clientY - drag.y) * k; + drag = { x: e.clientX, y: e.clientY }; + draw(); + }); + canvas.addEventListener('pointerup', () => { drag = null; }); + canvas.addEventListener('wheel', (e) => { e.preventDefault(); view.half = Math.max(0.05, Math.min(200, view.half * Math.exp(e.deltaY * 0.0012))); draw(); }, { passive: false }); + const ro = new ResizeObserver(draw); + ro.observe(canvas); + + analyze(input.value); + return { show: () => draw(), hide() {} }; +} diff --git a/live/wwwroot/views/representations.js b/live/wwwroot/views/representations.js new file mode 100644 index 0000000000..32bbb12d59 --- /dev/null +++ b/live/wwwroot/views/representations.js @@ -0,0 +1,451 @@ +import { $, html, escapeHtml, setChip, presets, codeBlock, CODE_BLOCK, tex, token, debounce, linkProgram, fullscreenTriangle, FULLSCREEN_VS, fitCanvas, rgb } from '../shared.js'; + +const PRESETS = [ + { label: 'A curve', formula: 'sin(x)^2 + cos(x) x / 2' }, + { label: 'A surface', formula: 'sin(x) cos(y) + (x^2 - y^2) / 12' }, + { label: 'A region', formula: 'x^2 + y^2 < 4 and y > x - 1' }, + { label: 'Logic', formula: '(a and b) or (a and not b) or (c and a)' }, + { label: 'An inequality', formula: 'x^3 - x > 0' }, + { label: 'A set', formula: '[1; 3) \\/ (2; 5] \\/ {7}' }, + { label: 'A number', formula: 'sqrt(2) + pi / 3' }, + { label: 'Shared parts', formula: '(x + 1)^2 - x^2 + sqrt((x + 1)^2 + 1)' }, + { label: 'A cubic', formula: 'x^3 - 6x^2 + 11x - 6' }, + { label: 'Fractions', formula: '1/(x - 1) + 1/(x + 1)' }, + { label: 'Roots in an interval', formula: 'sin(x) = 1/2 and x in [0; 2pi]' }, +]; + +// Two formulas each, for the question whether they are equal. +const PAIRS = [ + { label: 'Proved', formula: 'sin(x)^2 + cos(x)^2', other: '1' }, + { label: 'Proved, with conditions', formula: 'tan(x)', other: 'sin(x) / cos(x)' }, + { label: 'Refuted at a point', formula: 'sqrt(x^2)', other: 'x' }, + { label: 'Refuted off the real line', formula: 'abs(x)^2', other: 'x^2' }, + { label: 'Not decided', formula: '(x + 1)^2', other: 'x^2 + 2x + 1' }, +]; + +const MARKUP = ` +
+
+
+

One formula, every form AngouriMath gives it

+

Representations

+
+

Type any formula: a function of x, of x and y, a comparison, logic, a set or a number. AngouriMath parses it once and produces each representation below, including the picture that suits what it is.

+
+
+
Waiting for AngouriMath
+

+
+
+

Rendered

+

Simplified by AngouriMath

+

Other forms

+
+

Equal to a second formula?

+
+
+
+

+
+

Picture

+

Expression tree

+

Text, as AngouriMath prints it

+

Text in Unicode

Printed under MathS.Settings.UnicodeOutput. The parser reads every glyph back.

+

LaTeX source

+

SymPy

+

Shader

${CODE_BLOCK}
+
+
`; + +export function mount(section, am) { + section.classList.add('doc'); + html(section, MARKUP); + const input = $(section, '#forms-input'), chip = $(section, '[data-chip]'); + const setCode = codeBlock($(section, '[data-shader-card]')); + let picture = null; + + const other = $(section, '#forms-other'); + const press = presets($(section, '.presets'), PRESETS, (p) => { + input.value = p.formula; + other.value = ''; + press(p.label); + pressPair(null); + describe(); + }); + const pressPair = presets($(section, '[data-pairs]'), PAIRS, (p) => { + input.value = p.formula; + other.value = p.other; + press(null); + pressPair(p.label); + describe(); + }); + input.value = PRESETS[0].formula; + press(PRESETS[0].label); + const later = debounce(() => describe(), 400); + input.addEventListener('input', () => { press(null); pressPair(null); later(); }); + const compareLater = debounce(() => compare(), 400); + other.addEventListener('input', () => { pressPair(null); compareLater(); }); + + let generation = 0; + async function describe() { + const mine = ++generation, text = input.value, t0 = performance.now(); + let r; + try { + r = await am.json('RepresentationsJs', 'Describe', [text]); + } catch (e) { + if (mine === generation) { setChip(chip, 'bad', 'AngouriMath stopped'); $(section, '[data-error]').textContent = e.message; } + return; + } + if (mine !== generation) return; + $(section, '[data-timing]').textContent = `${Math.round(performance.now() - t0)} ms`; + if (!r.ok) { + setChip(chip, 'warn', 'Not a formula yet'); + $(section, '[data-error]').textContent = r.error; + return; + } + $(section, '[data-error]').textContent = ''; + const kinds = { curve: 'A function of one variable', surface: 'A function of two variables', region: 'A region of the plane', + logic: 'Logic', set: 'A set of numbers', value: 'A number', other: 'An expression' }; + setChip(chip, 'ok', kinds[r.kind] || 'An expression'); + tex($(section, '[data-latex]'), r.latex); + tex($(section, '[data-simplified]'), r.simplifiedLatex); + $(section, '[data-simplified-text]').textContent = r.simplified === r.text ? 'Already as simple as AngouriMath makes it.' : r.simplified; + showForms($(section, '[data-forms]'), r.forms, r.text); + $(section, '[data-text]').textContent = r.text; + $(section, '[data-unicode]').textContent = r.unicode || r.text; + $(section, '[data-latex-source]').textContent = r.latex; + $(section, '[data-sympy]').textContent = r.sympy || 'No SymPy form.'; + $(section, '[data-shader-card]').hidden = !r.glsl; + if (r.glsl) setCode(r.glsl, r.hlsl || '', 'The formula as a shader function of p; repeated parts are computed once.'); + drawTree($(section, '[data-tree]'), r.tree); + $(section, '[data-tree-note]').textContent = r.nodes === r.distinct + ? `${r.nodes} nodes, all different.` + : `${r.nodes} nodes, of which ${r.distinct} are different: a repeated subtree is computed once in the shader.`; + compare(); + picture?.dispose?.(); + picture = await drawPicture(r, mine); + } + describe(); + + let comparison = 0; + async function compare() { + const mine = ++comparison, box = $(section, '[data-equal]'), note = $(section, '[data-equal-note]'); + const second = other.value.trim(); + if (!second) { + box.replaceChildren(); + note.textContent = 'Type a second formula, or pick a pair. AngouriMath answers equal, not equal or not decided, and says what the answer rests on.'; + return; + } + const t0 = performance.now(); + let r; + try { + r = await am.json('RepresentationsJs', 'Compare', [input.value, second]); + } catch (e) { + if (mine === comparison) { box.replaceChildren(); note.textContent = e.message; } + return; + } + if (mine !== comparison) return; + if (!r.ok) { box.replaceChildren(); note.textContent = r.error; return; } + showAnswers(box, r.answers); + note.textContent = `By MathS.AreEqual, with at most ${r.steps.toLocaleString('en')} steps of work for a question: ${Math.round(performance.now() - t0)} ms.`; + } + + async function drawPicture(r, mine) { + const box = $(section, '[data-picture]'), title = $(section, '[data-picture-title]'), note = $(section, '[data-picture-note]'); + box.replaceChildren(); + note.textContent = ''; + if (r.kind === 'curve') { + title.textContent = `Plot of the function of ${r.vars[0]}`; + const samples = await am.call('RepresentationsJs', 'Sample', [-6, 6, 600]); + if (mine !== generation) return null; + return plotCurve(box, samples, -6, 6); + } + if (r.kind === 'surface' || r.kind === 'region') { + title.textContent = r.kind === 'region' ? 'The region, on the GPU' : 'Heat map with level curves, on the GPU'; + note.textContent = `${r.vars[0]} runs left to right and ${r.vars[1]} bottom to top; the shorter side spans −4 to 4, with grid lines one unit apart. Drawn by the GLSL in the Shader card.`; + return r.glsl ? heatMap(box, r.glsl, r.kind === 'region') : null; + } + if (r.kind === 'logic' && r.truth) { + title.textContent = 'Truth table'; + box.append(truthTable(r.truth)); + return null; + } + if (r.kind === 'set') { + title.textContent = 'On the number line'; + if (r.solved) note.textContent = `Solved by AngouriMath: ${r.solved}`; + if (r.note) note.textContent = r.note; + if (r.intervals) box.append(numberLine(r.intervals)); + return null; + } + if (r.kind === 'value') { + title.textContent = 'Value'; + const p = document.createElement('p'); + p.style.cssText = 'margin:0;font:28px/1.2 var(--font-mono);overflow-wrap:anywhere'; + p.textContent = r.value; + box.append(p); + return null; + } + title.textContent = 'Picture'; + note.textContent = 'Pictures are drawn for formulas in up to two variables, logic and sets.'; + return null; + } + + return { show() {}, hide() {} }; +} + +// ---------------------------------------------------------------- forms + +/** The rewrites side by side, and the forms simplify weighs, simplest first. */ +function showForms(box, forms, text) { + box.replaceChildren(); + const add = (label, latex, foot) => { + const div = document.createElement('div'); + div.className = 'labelled'; + div.innerHTML = `${escapeHtml(label)}
${foot ? `

${escapeHtml(foot)}

` : ''}`; + tex(div.children[1], latex); + box.append(div); + }; + const same = (form) => (form.text === text ? 'As written.' : ''); + add('Expanded: products multiplied out', forms.expanded.latex, same(forms.expanded)); + add('Factorised: common factors gathered, polynomials factored', forms.factorized.latex, same(forms.factorized)); + add('Normalised: one tidying pass, without a search', forms.normalized.latex, same(forms.normalized)); + const alternatives = document.createElement('div'); + alternatives.className = 'labelled alternatives'; + alternatives.innerHTML = 'Forms simplify weighs against each other, simplest first
    '; + forms.alternatives.forEach((a, i) => { + const li = document.createElement('li'); + li.innerHTML = `${i + 1}
    `; + tex(li.lastChild, a.latex); + alternatives.lastChild.append(li); + }); + box.append(alternatives); +} + +/** MathS.AreEqual's answer in each domain: the verdict, then the proof's rules or the point that refutes. */ +function showAnswers(box, answers) { + const domains = { complex: 'Over the complex numbers', real: 'Over the real numbers' }; + const verdicts = { Equal: ['ok', 'Equal'], NotEqual: ['bad', 'Not equal'], Unknown: ['warn', 'Not decided'] }; + box.replaceChildren(...answers.map((a) => { + const div = document.createElement('div'); + div.className = 'labelled'; + const [kind, word] = verdicts[a.verdict]; + div.innerHTML = `${domains[a.domain]}
    ${word}
    `; + const foot = document.createElement('p'); + foot.className = 'foot'; + if (a.verdict === 'Equal') { + foot.textContent = a.sound + ? 'Proved by rewrite rules that hold with no side condition.' + : `Proved wherever both sides have a value, by rules that carry side conditions: ${a.rules.join('; ')}.`; + } else if (a.verdict === 'NotEqual') { + if (a.atLatex) { + const at = document.createElement('div'); + at.className = 'tex'; + tex(at, a.atLatex); + div.append(at); + } + foot.textContent = `${a.atLatex ? 'At this point the' : 'The'} first is ${a.leftAt} and the second is ${a.rightAt}.`; + } else { + foot.textContent = a.finished + ? 'No proof within the rules, and no point found where the two differ. That does not say they are unequal.' + : 'The steps ran out before a proof or a differing point was found. That does not say they are unequal.'; + } + div.append(foot); + return div; + })); +} + +// ---------------------------------------------------------------- pictures + +function plotCurve(box, ys, x0, x1) { + const canvas = document.createElement('canvas'); + canvas.style.height = '280px'; + box.append(canvas); + const draw = () => { + const [w, h] = fitCanvas(canvas, 2); + const ctx = canvas.getContext('2d'); + const finite = ys.filter((y) => y !== null && Number.isFinite(y)).sort((a, b) => a - b); + let lo = finite.length ? finite[Math.floor(finite.length * 0.02)] : -1, hi = finite.length ? finite[Math.ceil(finite.length * 0.98) - 1] : 1; + if (hi - lo < 1e-9) { lo -= 1; hi += 1; } + const pad = (hi - lo) * 0.12; + lo -= pad; hi += pad; + const X = (x) => (x - x0) / (x1 - x0) * w, Y = (y) => h - (y - lo) / (hi - lo) * h; + ctx.clearRect(0, 0, w, h); + ctx.lineWidth = 1; + ctx.strokeStyle = token('--rule'); + ctx.fillStyle = token('--ink-soft'); + ctx.font = `${11 * (w / canvas.clientWidth)}px ${token('--font-body')}`; + for (let x = Math.ceil(x0); x <= x1; x++) { + ctx.beginPath(); ctx.moveTo(X(x), 0); ctx.lineTo(X(x), h); ctx.stroke(); + } + const step = niceStep((hi - lo) / 5); + for (let y = Math.ceil(lo / step) * step; y <= hi; y += step) { + ctx.beginPath(); ctx.moveTo(0, Y(y)); ctx.lineTo(w, Y(y)); ctx.stroke(); + ctx.fillText(+y.toFixed(6) + '', 4, Y(y) - 3); + } + ctx.strokeStyle = token('--ink-soft'); + ctx.beginPath(); ctx.moveTo(X(0), 0); ctx.lineTo(X(0), h); ctx.moveTo(0, Y(0)); ctx.lineTo(w, Y(0)); ctx.stroke(); + ctx.strokeStyle = token('--plot-1'); + ctx.lineWidth = 2.2 * (w / canvas.clientWidth); + ctx.beginPath(); + let pen = false; + ys.forEach((y, i) => { + if (y === null || !Number.isFinite(y)) { pen = false; return; } + const px = X(x0 + (x1 - x0) * i / (ys.length - 1)), py = Y(y); + pen ? ctx.lineTo(px, py) : ctx.moveTo(px, py); + pen = true; + }); + ctx.stroke(); + }; + draw(); + const ro = new ResizeObserver(draw); + ro.observe(canvas); + return { dispose: () => ro.disconnect() }; +} + +export function niceStep(raw) { + const p = Math.pow(10, Math.floor(Math.log10(raw))); + const m = raw / p; + return (m < 1.5 ? 1 : m < 3.5 ? 2 : m < 7.5 ? 5 : 10) * p; +} + +function heatMap(box, glsl, isRegion) { + const canvas = document.createElement('canvas'); + canvas.style.height = '340px'; + box.append(canvas); + const gl = canvas.getContext('webgl2', { antialias: false }); + if (!gl) { box.textContent = 'This browser has no WebGL2.'; return null; } + const fs = `#version 300 es +precision highp float; +in vec2 vNdc; +uniform vec2 uScale; +uniform vec3 uLo, uMid, uHi, uInk; +out vec4 outColor; +${glsl} +void main() { + vec2 p = vNdc * uScale; + vec2 grid = abs(fract(p + 0.5) - 0.5) / fwidth(p); + float gridLine = 1.0 - min(min(grid.x, grid.y), 1.0); + vec2 axis = abs(p) / fwidth(p); + float axisLine = 1.0 - min(min(axis.x, axis.y), 1.0); + vec3 col; + ${isRegion + ? 'col = f(p) ? mix(uMid, uHi, 0.55) : uMid;' + : `float v = f(p); + float t = tanh(v * 0.6); + col = t < 0.0 ? mix(uMid, uLo, -t) : mix(uMid, uHi, t); + float level = abs(fract(v * 2.0 + 0.5) - 0.5) / max(fwidth(v * 2.0), 1e-5); + col = mix(col, uInk, 0.35 * (1.0 - min(level, 1.0))); + if (isnan(v)) col = uMid * 0.6;`} + col = mix(col, uInk, 0.12 * gridLine + 0.45 * axisLine); + outColor = vec4(col, 1.0); +}`; + let prog; + try { + prog = linkProgram(gl, FULLSCREEN_VS, fs); + } catch (e) { box.textContent = `The GPU did not accept the shader: ${e.message}`; return null; } + const vao = fullscreenTriangle(gl); + const draw = () => { + const [w, h] = fitCanvas(canvas, 2); + gl.viewport(0, 0, w, h); + gl.useProgram(prog.program); + const aspect = w / h; + gl.uniform2f(prog.loc.uScale, aspect >= 1 ? 4 * aspect : 4, aspect >= 1 ? 4 : 4 / aspect); + gl.uniform3fv(prog.loc.uLo, rgb('--plot-1')); + gl.uniform3fv(prog.loc.uHi, rgb('--plot-2')); + gl.uniform3fv(prog.loc.uMid, rgb('--surface')); + gl.uniform3fv(prog.loc.uInk, rgb('--ink')); + gl.bindVertexArray(vao); + gl.drawArrays(gl.TRIANGLES, 0, 3); + }; + draw(); + const ro = new ResizeObserver(draw); + ro.observe(canvas); + return { dispose: () => { ro.disconnect(); gl.getExtension('WEBGL_lose_context')?.loseContext(); } }; +} + +export function truthTable(truth) { + const wrap = document.createElement('div'); + wrap.className = 'scroll-x'; + // The Logic tab's senses mode adds a column per output and marks impossible rows, whose values + // show as dashes. + const n = truth.vars.length, outputs = truth.outputs ?? ['value']; + const head = [...truth.vars, ...outputs].map((v) => `${escapeHtml(v)}`).join(''); + const rows = truth.rows.map((row, i) => { + const possible = truth.possible?.[i] ?? true, hit = row.slice(n).some(Boolean); + const cells = row.map((b, j) => j >= n && !possible ? '–' : `${b ? '1' : '0'}`); + return `${cells.join('')}`; + }).join(''); + wrap.innerHTML = `${head}${rows}
    `; + return wrap; +} + +/** Intervals and points from the C# side as an SVG number line. */ +export function numberLine(parts) { + const ends = []; + for (const p of parts) { + if (p.point !== undefined) ends.push(p.point); + if (p.lo !== null && p.lo !== undefined) ends.push(p.lo); + if (p.hi !== null && p.hi !== undefined) ends.push(p.hi); + } + let lo = ends.length ? Math.min(...ends) : -1, hi = ends.length ? Math.max(...ends) : 1; + if (hi - lo < 1e-9) { lo -= 1; hi += 1; } + const pad = (hi - lo) * 0.25; + lo -= pad; hi += pad; + const W = 720, H = 92, X = (x) => 20 + (x - lo) / (hi - lo) * (W - 40), axisY = 50; + // CSS variables do not resolve in SVG presentation attributes, so colours go in style. + const soft = 'fill:var(--ink-soft)', axis = 'stroke:var(--ink-soft);stroke-width:1.2', ink = 'fill:var(--ink)'; + let svg = ``; + svg += ``; + const step = niceStep((hi - lo) / 8); + for (let x = Math.ceil(lo / step) * step; x <= hi; x += step) { + svg += ``; + svg += `${+x.toFixed(6)}`; + } + const dot = (x, closed) => ``; + const label = (x, text) => `${escapeHtml(text)}`; + for (const p of parts) { + if (p.point !== undefined) { + svg += dot(p.point, true) + label(p.point, p.text); + continue; + } + const a = p.lo ?? lo, b = p.hi ?? hi; + svg += ``; + if (p.lo === null) svg += ``; + else svg += dot(p.lo, p.loClosed) + label(p.lo, p.loText); + if (p.hi === null) svg += ``; + else svg += dot(p.hi, p.hiClosed) + label(p.hi, p.hiText); + } + const box = document.createElement('div'); + box.className = 'scroll-x'; + box.innerHTML = `${svg}`; + return box; +} + +/** A tidy tree: leaves side by side, each parent centred over its children. */ +export function drawTree(box, tree) { + const nodes = []; + let leaves = 0, depth = 0; + (function place(n, d) { + depth = Math.max(depth, d); + const node = { label: n.t, d, kids: (n.c || []).map((c) => place(c, d + 1)) }; + node.x = node.kids.length ? (node.kids[0].x + node.kids[node.kids.length - 1].x) / 2 : leaves++; + nodes.push(node); + return node; + })(tree, 0); + const DX = 54, DY = 54, W = Math.max(leaves * DX, 120), H = (depth + 1) * DY; + const pos = (n) => [n.x * DX + DX / 2, n.d * DY + 22]; + let svg = ''; + for (const n of nodes) + for (const k of n.kids) { + const [x1, y1] = pos(n), [x2, y2] = pos(k); + svg += ``; + } + for (const n of nodes) { + const [x, y] = pos(n), leaf = !n.kids.length; + const label = n.label.length > 9 ? n.label.slice(0, 8) + '…' : n.label; + const w = Math.max(26, label.length * 7.4 + 12); + svg += ``; + svg += `${escapeHtml(label)}`; + } + box.innerHTML = `${svg}`; +} diff --git a/live/wwwroot/views/shapes.js b/live/wwwroot/views/shapes.js new file mode 100644 index 0000000000..e418a6d32f --- /dev/null +++ b/live/wwwroot/views/shapes.js @@ -0,0 +1,234 @@ +import { $, html, setChip, presets, codeBlock, CODE_BLOCK, collapsible, linkProgram, fullscreenTriangle, FULLSCREEN_VS, fitCanvas, loop, tex, debounce } from '../shared.js'; + +const PRESETS = [ + { label: 'Torus', formula: 'sqrt((sqrt(x^2 + z^2) - 1)^2 + y^2) - 0.4', + note: 'A true distance: f is the distance to the surface. Its mean curvature is positive all round; switch to Gaussian curvature to see the saddle-shaped inside turn negative.' }, + { label: 'Heart', formula: '(x^2 + 9/4 z^2 + y^2 - 1)^3 - x^2 y^3 - 9/80 z^2 y^3', + note: 'Taubin’s heart, a degree-6 polynomial and no distance at all: marching steps by f / |∇f|, which only works with the exact gradient.' }, + { label: 'Blobs', formula: '-log(e^(-8 (sqrt((x - 0.55)^2 + y^2 + z^2) - 0.5)) + e^(-8 (sqrt((x + 0.55)^2 + y^2 + z^2) - 0.5)) + e^(-8 (sqrt(x^2 + (y - 0.6)^2 + z^2) - 0.42))) / 8', + note: 'Three spheres joined by a smooth minimum (log-sum-exp), which AngouriMath differentiates like anything else.' }, + { label: 'Gyroid', formula: 'sin(4x) cos(4y) + sin(4y) cos(4z) + sin(4z) cos(4x)', + note: 'A triply periodic minimal-like surface, cut by the bounding sphere. Mean curvature near zero everywhere: try the Gaussian colouring.' }, + { label: 'Rounded cube', formula: 'x^8 + y^8 + z^8 - 1', + note: 'Flat faces, curvature concentrated along the edges.' }, + { label: 'Hard max', formula: 'max(max(abs(x), abs(y)), abs(z)) - 1', + note: 'A cube as a max of distances. AngouriMath does not differentiate max, and says so instead of guessing.' }, +]; + +const FS = (fns) => `#version 300 es +precision highp float; +in vec2 vNdc; +uniform vec3 uEye, uFwd, uRight, uUp; +uniform vec2 uTan; +uniform float uShift; +uniform int uMode; +uniform float uRadius; +uniform vec3 uBg0, uBg1; +out vec4 outColor; +${fns} +vec3 diverging(float t) { + vec3 neg = vec3(0.16, 0.42, 0.78), mid = vec3(0.93, 0.92, 0.88), pos = vec3(0.86, 0.36, 0.12); + return t < 0.0 ? mix(mid, neg, -t) : mix(mid, pos, t); +} +void main() { + vec3 rd = normalize(uFwd + (vNdc.x * uTan.x - uShift) * uRight + vNdc.y * uTan.y * uUp); + vec3 ro = uEye; + vec3 bg = mix(uBg0, uBg1, 0.5 + 0.5 * vNdc.y); + float b = dot(ro, rd), c = dot(ro, ro) - uRadius * uRadius, disc = b * b - c; + if (disc < 0.0) { outColor = vec4(bg, 1.0); return; } + float t = max(-b - sqrt(disc), 0.0), tEnd = -b + sqrt(disc); + // March by f / |grad f|, the first-order distance the exact gradient gives; a sign change + // brackets the surface, and bisection finds it. + vec4 prev = fieldGrad(ro + rd * t); + float tPrev = t; + bool hit = false; + for (int i = 0; i < 240; i++) { + vec4 r = fieldGrad(ro + rd * t); + if (i > 0 && sign(r.x) != sign(prev.x)) { + float a = tPrev, z = t, s0 = sign(prev.x); + for (int k = 0; k < 16; k++) { + float m = 0.5 * (a + z); + if (sign(field(ro + rd * m)) == s0) a = m; else z = m; + } + t = 0.5 * (a + z); + hit = true; + break; + } + float d = r.x / max(length(r.yzw), 1e-3); + if (abs(d) < 1e-4) { hit = true; break; } + tPrev = t; + prev = r; + t += clamp(abs(d) * 0.8, 2e-3, 0.06); + if (t > tEnd) break; + } + if (!hit) { outColor = vec4(bg, 1.0); return; } + vec3 p = ro + rd * t; + vec3 g = fieldGrad(p).yzw; + vec3 Hd, Ho; + fieldHess(p, Hd, Ho); + mat3 H = mat3(Hd.x, Ho.x, Ho.y, Ho.x, Hd.y, Ho.z, Ho.y, Ho.z, Hd.z); + float gn = max(length(g), 1e-6); + vec3 n = g / gn; + if (dot(n, rd) > 0.0) n = -n; + // Mean curvature (|g|^2 tr H - g.Hg) / 2|g|^3 and Gaussian g.adj(H)g / |g|^4. + float mean = (gn * gn * (Hd.x + Hd.y + Hd.z) - dot(g, H * g)) / (2.0 * gn * gn * gn); + mat3 adj = mat3( + Hd.y * Hd.z - Ho.z * Ho.z, Ho.y * Ho.z - Ho.x * Hd.z, Ho.x * Ho.z - Ho.y * Hd.y, + Ho.y * Ho.z - Ho.x * Hd.z, Hd.x * Hd.z - Ho.y * Ho.y, Ho.x * Ho.y - Hd.x * Ho.z, + Ho.x * Ho.z - Ho.y * Hd.y, Ho.x * Ho.y - Hd.x * Ho.z, Hd.x * Hd.y - Ho.x * Ho.x); + float gauss = dot(g, adj * g) / (gn * gn * gn * gn); + vec3 base = uMode == 0 ? diverging(tanh(mean * 0.5)) : uMode == 1 ? diverging(tanh(gauss * 0.4)) : 0.5 + 0.5 * n; + vec3 light = normalize(vec3(0.5, 0.8, 0.4)); + float diff = max(dot(n, light), 0.0); + float spec = pow(max(dot(reflect(rd, n), light), 0.0), 40.0); + float rim = pow(1.0 - max(dot(n, -rd), 0.0), 3.0); + vec3 col = base * (0.28 + 0.72 * diff) + 0.25 * spec + 0.12 * rim; + if (isnan(col.x)) col = vec3(0.95, 0.12, 0.55); + outColor = vec4(col, 1.0); +}`; + +const MARKUP = ` + +`; + +export function mount(section, am) { + html(section, MARKUP); + const canvas = $(section, 'canvas'), panel = $(section, '.panel'), chip = $(section, '[data-chip]'); + collapsible(panel); + const setCode = codeBlock($(section, '[data-code]')); + const gl = canvas.getContext('webgl2', { antialias: false }); + const vao = gl && fullscreenTriangle(gl); + let prog = null; + const view = { yaw: 0.6, pitch: 0.35, dist: 5.6, spinning: !matchMedia('(prefers-reduced-motion: reduce)').matches, mode: 0 }; + + const animation = loop((dt) => { + if (!gl || !prog) return; + if (view.spinning) view.yaw += dt * 0.25; + const [w, h] = fitCanvas(canvas, 1.5); + gl.viewport(0, 0, w, h); + const cp = Math.cos(view.pitch), eye = [view.dist * cp * Math.sin(view.yaw), view.dist * Math.sin(view.pitch), view.dist * cp * Math.cos(view.yaw)]; + const fwd = eye.map((v) => -v / view.dist); + const rl = Math.hypot(fwd[2], fwd[0]); + const right = [-fwd[2] / rl, 0, fwd[0] / rl]; + const up = [right[1] * fwd[2] - right[2] * fwd[1], right[2] * fwd[0] - right[0] * fwd[2], right[0] * fwd[1] - right[1] * fwd[0]]; + const tanY = Math.tan(22 * Math.PI / 180); + const dark = matchMedia('(prefers-color-scheme: dark)').matches && document.documentElement.dataset.theme !== 'light' || document.documentElement.dataset.theme === 'dark'; + gl.useProgram(prog.program); + gl.uniform3fv(prog.loc.uEye, eye); + gl.uniform3fv(prog.loc.uFwd, fwd); + gl.uniform3fv(prog.loc.uRight, right); + gl.uniform3fv(prog.loc.uUp, up); + gl.uniform2f(prog.loc.uTan, tanY * w / h, tanY); + // With the panel on the left, centre the shape in the space to its right. + gl.uniform1f(prog.loc.uShift, canvas.clientWidth > 900 ? 0.22 * tanY * w / h : 0); + gl.uniform1i(prog.loc.uMode, view.mode); + gl.uniform1f(prog.loc.uRadius, 2.0); + gl.uniform3fv(prog.loc.uBg0, dark ? [0.03, 0.06, 0.09] : [0.80, 0.86, 0.89]); + gl.uniform3fv(prog.loc.uBg1, dark ? [0.07, 0.12, 0.16] : [0.95, 0.97, 0.98]); + gl.bindVertexArray(vao); + gl.drawArrays(gl.TRIANGLES, 0, 3); + }); + + let generation = 0; + async function generate(text) { + const mine = ++generation, t0 = performance.now(); + setChip(chip, '', 'Differentiating'); + let r; + try { + r = await am.json('ShapesJs', 'Generate', [text]); + } catch (e) { + if (mine === generation) { setChip(chip, 'bad', 'AngouriMath stopped'); $(section, '[data-error]').textContent = e.message; } + return; + } + if (mine !== generation) return; + $(section, '[data-timing]').textContent = `${Math.round(performance.now() - t0)} ms`; + if (!r.ok) { + setChip(chip, 'bad', 'No shader for this one'); + $(section, '[data-error]').textContent = `${r.error} The picture keeps the last shape that worked.`; + return; + } + if (!gl) { setChip(chip, 'warn', 'No WebGL2 here'); return; } + try { + const next = linkProgram(gl, FULLSCREEN_VS, FS(r.glsl)); + if (prog) gl.deleteProgram(prog.program); + prog = next; + } catch (e) { + setChip(chip, 'bad', 'The GPU did not accept the shader'); + $(section, '[data-error]').textContent = e.message; + return; + } + setChip(chip, 'ok', 'Gradient and Hessian generated'); + $(section, '[data-error]').textContent = ''; + tex($(section, '[data-latex]'), r.latex); + setCode(r.glsl, r.hlsl, 'field() for the sign test, fieldGrad() for each step, fieldHess() once at the surface.'); + } + + const input = $(section, '#shapes-input'), note = $(section, '[data-note]'); + const press = presets($(section, '.presets'), PRESETS, (p) => { + input.value = p.formula; + note.textContent = p.note; + press(p.label); + generate(p.formula); + }); + input.value = PRESETS[0].formula; + note.textContent = PRESETS[0].note; + press(PRESETS[0].label); + const later = debounce(() => generate(input.value), 450); + input.addEventListener('input', () => { press(null); note.textContent = ''; later(); }); + + $(section, '#shapes-mode').addEventListener('change', (e) => { view.mode = +e.target.value; }); + const spin = $(section, '[data-spin]'); + const syncSpin = () => { spin.textContent = view.spinning ? 'Stop turning' : 'Turn'; }; + spin.addEventListener('click', () => { view.spinning = !view.spinning; syncSpin(); }); + syncSpin(); + if (matchMedia('(min-width: 900px)').matches) $(section, '[data-code]').open = false; + + let drag = null; + canvas.addEventListener('pointerdown', (e) => { drag = { x: e.clientX, y: e.clientY }; canvas.setPointerCapture(e.pointerId); }); + canvas.addEventListener('pointermove', (e) => { + if (!drag) return; + view.yaw -= (e.clientX - drag.x) * 0.008; + view.pitch = Math.max(-1.4, Math.min(1.4, view.pitch + (e.clientY - drag.y) * 0.008)); + drag = { x: e.clientX, y: e.clientY }; + }); + canvas.addEventListener('pointerup', () => { drag = null; }); + canvas.addEventListener('wheel', (e) => { e.preventDefault(); view.dist = Math.max(2.4, Math.min(9, view.dist * Math.exp(e.deltaY * 0.001))); }, { passive: false }); + + generate(input.value); + return { show: () => animation.start(), hide: () => animation.stop() }; +} diff --git a/live/wwwroot/views/waves.js b/live/wwwroot/views/waves.js new file mode 100644 index 0000000000..3753647d35 --- /dev/null +++ b/live/wwwroot/views/waves.js @@ -0,0 +1,479 @@ +import { $, html, setChip, presets, codeBlock, CODE_BLOCK, collapsible, linkProgram, fitCanvas, loop, fullscreenTriangle, FULLSCREEN_VS } from '../shared.js'; + +// A wind sea as WAVE_COUNT wave trains, longest first. A handful of plane waves interfere into a +// lattice the eye finds at once; a sea is a spectrum. So the wavelengths are one per band of a +// logarithmic split of LONGEST..SHORTEST, jittered within the band so that none is a multiple of +// another; the headings spread about the wind, wider for shorter waves; each train starts at a +// random phase (an offset of the surface point); and the weights follow Pierson–Moskowitz. +// In deep water that spectrum gives each logarithmic band the same slope variance above the peak +// and exp(-1.25 (λ/λp)²) of it below, so weight² is that factor, normalised to a sum of 1: the +// slider is then the sea's RMS slope. Seeded, so the sea is the same on every visit. +const WAVE_COUNT = 32, LONGEST = 80, SHORTEST = 1.2, PEAK = 35; +const WAVES = () => { + let seed = 0x5eed; + const random = () => { + seed = (seed + 0x6d2b79f5) | 0; + let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; + const gaussian = () => Math.sqrt(-2 * Math.log(1 - random())) * Math.cos(2 * Math.PI * random()); + const waves = Array.from({ length: WAVE_COUNT }, (_, i) => { + const lambda = LONGEST * Math.pow(SHORTEST / LONGEST, (i + random()) / WAVE_COUNT); + const spread = 0.25 + 0.55 * i / (WAVE_COUNT - 1); + return { + lambda, k: 2 * Math.PI / lambda, turn: spread * gaussian(), off: [2000 * random(), 2000 * random()], + weight: Math.exp(-0.625 * (lambda / PEAK) ** 2), t: 0, omega: NaN, + }; + }); + const norm = Math.hypot(...waves.map((w) => w.weight)); + for (const w of waves) w.weight /= norm; + return waves; +}; +const LONG_LABEL = `${Math.round(WAVES()[0].lambda)} m`, SHORT_LABEL = `${WAVES()[WAVE_COUNT - 1].lambda.toFixed(1)} m`; + +const PRESETS = [ + { label: 'Any depth', formula: 'sqrt(g k (1 - 2/(e^(2 k h) + 1)))', + note: 'ω² = g k tanh(k h), with tanh written so that 32-bit floats never overflow.' }, + { label: 'tanh as typed', formula: 'sqrt(g k tanh(k h))', + note: 'AngouriMath reads tanh(x) as (e^2x − 1)/(e^2x + 1), and on the GPU e^2x overflows once k h passes 44. The shader printer writes the ratio as 1 − 2/(e^2x + 1), which is 1 there: drag the depth past 14 m.' }, + { label: 'Deep water', formula: 'sqrt(g k)', note: 'The depth drops out, and long waves outrun short ones.' }, + { label: 'Shallow water', formula: 'k sqrt(g h)', note: 'Every wave travels at √(g h), whatever its length.' }, + { label: 'A typo', formula: 'sqrt(g k h)', note: 'The depth in the wrong place. The units check finds where.' }, +]; + +// The default formula's shader, printed by the same code before this page was built, so the +// sea is there while AngouriMath loads. +const INITIAL_GLSL = `vec3 waveHeightSlope(vec2 p, float t, float A, float k, float h, vec2 dir) +{ + vec3 r; + float am0 = ((k * ((dir.x * p.x) + (dir.y * p.y))) - (sqrt(((WAVE_G * k) * (1.0 - (2.0 / (exp(((2.0 * k) * h)) + 1.0))))) * t)); + float am1 = cos(am0); + r.x = (A * sin(am0)); + r.y = ((am1 * (dir.x * k)) * A); + r.z = ((am1 * (dir.y * k)) * A); + return r; +} +`; +const INITIAL_HLSL = `float3 waveHeightSlope(float2 p, float t, float A, float k, float h, float2 dir) +{ + float3 r; + float am0 = ((k * ((dir.x * p.x) + (dir.y * p.y))) - (sqrt(((WAVE_G * k) * (1.0 - (2.0 / (exp(((2.0 * k) * h)) + 1.0))))) * t)); + float am1, am2; + sincos(am0, am1, am2); + r.x = (A * am1); + r.y = ((am2 * (dir.x * k)) * A); + r.z = ((am2 * (dir.y * k)) * A); + return r; +} +`; + +const GRID = 320, EXTENT = 900, FOV = 55 * Math.PI / 180; +const SUN = (() => { const v = [0.0, 0.22, -1.0], l = Math.hypot(...v); return v.map((x) => x / l); })(); + +const HEADER = `#version 300 es +precision highp float; +precision highp int; +#define WAVE_COUNT ${WAVE_COUNT} +uniform vec4 uWave[WAVE_COUNT]; // A, k, t, unused +uniform vec4 uDirOff[WAVE_COUNT]; // direction of travel, offset of the surface point +uniform float uDepth; +uniform vec3 uCam; +uniform vec3 uSun; +#define WAVE_G 9.81 +`; + +const SKY = ` +vec3 sky(vec3 d) { + vec3 horizon = vec3(0.72, 0.80, 0.84); + vec3 zenith = vec3(0.17, 0.37, 0.62); + vec3 below = vec3(0.03, 0.08, 0.12); + vec3 c = d.y >= 0.0 ? mix(horizon, zenith, pow(d.y, 0.45)) : mix(horizon, below, smoothstep(0.0, 0.25, -d.y)); + float s = max(dot(d, uSun), 0.0); + return c + vec3(1.0, 0.86, 0.62) * (0.12 * pow(s, 8.0) + 0.3 * pow(s, 90.0)) + + vec3(1.0, 0.95, 0.86) * 3.0 * smoothstep(0.99984, 0.99993, s); +} +`; + +const SEA_VS = ` +in vec2 aGrid; +uniform mat4 uViewProj; +uniform float uExtent; +out vec3 vWorld; +void main() { + // Quadratic spacing: dense under the camera, coarse at the horizon. + vec2 u = aGrid; + vec2 xz = uCam.xz + sign(u) * u * u * uExtent; + float cell = 4.0 * max(abs(u.x), abs(u.y)) * uExtent / ${GRID.toFixed(1)}; + float y = 0.0; + for (int i = 0; i < WAVE_COUNT; i++) { + float lambda = 6.2831853 / uWave[i].y; + float w = 1.0 - smoothstep(0.25 * lambda, 0.5 * lambda, cell); + if (w > 0.0) + y += w * waveHeightSlope(xz + uDirOff[i].zw, uWave[i].z, uWave[i].x, uWave[i].y, uDepth, uDirOff[i].xy).x; + } + vWorld = vec3(xz.x, y, xz.y); + gl_Position = uViewProj * vec4(vWorld, 1.0); +} +`; + +const SEA_FS = ` +in vec3 vWorld; +uniform vec3 uBody; +uniform float uMaxA; +out vec4 outColor; +void main() { + // The normal comes from the exact slope at every pixel, not from the mesh. Waves shorter + // than the pixel footprint fade out instead of sparkling. + vec2 xz = vWorld.xz; + float footprint = max(length(dFdx(xz)), length(dFdy(xz))); + vec2 slope = vec2(0.0); + bool broken = false; + for (int i = 0; i < WAVE_COUNT; i++) { + float lambda = 6.2831853 / uWave[i].y; + float w = 1.0 - smoothstep(0.15 * lambda, 0.5 * lambda, footprint); + if (w <= 0.0) continue; + vec3 r = waveHeightSlope(xz + uDirOff[i].zw, uWave[i].z, uWave[i].x, uWave[i].y, uDepth, uDirOff[i].xy); + if (isnan(r.y) || isinf(r.y) || isnan(r.z) || isinf(r.z)) broken = true; + slope += w * r.yz; + } + vec3 n = normalize(vec3(-slope.x, 1.0, -slope.y)); + vec3 v = normalize(uCam - vWorld); + float fresnel = 0.02 + 0.98 * pow(1.0 - clamp(dot(n, v), 0.0, 1.0), 5.0); + vec3 r = reflect(-v, n); + r.y = abs(r.y); + float crest = clamp(vWorld.y / max(uMaxA, 1e-3) * 0.5 + 0.5, 0.0, 1.0); + vec3 body = uBody * (0.75 + 0.5 * crest); + vec3 col = mix(body, sky(r), fresnel) + vec3(1.0, 0.9, 0.72) * 2.5 * pow(max(dot(r, uSun), 0.0), 700.0); + float dist = length(uCam - vWorld); + col = mix(col, sky(normalize(vec3(-v.x, 0.0, -v.z))), 1.0 - exp(-dist * 0.0022)); + if (broken) col = mix(col, vec3(0.95, 0.12, 0.55), 0.85); + outColor = vec4(min(col, vec3(1.0)), 1.0); +} +`; + +const SKY_FS = ` +in vec2 vNdc; +uniform vec3 uFwd, uRight, uUp; +uniform vec2 uTan; +out vec4 outColor; +void main() { + vec3 d = normalize(uFwd + vNdc.x * uTan.x * uRight + vNdc.y * uTan.y * uUp); + outColor = vec4(min(sky(d), vec3(1.0)), 1.0); +} +`; + +const MARKUP = ` + +`; + +export function mount(section, am) { + html(section, MARKUP); + const panel = $(section, '.panel'), canvas = $(section, 'canvas'); + collapsible(panel); + const setCode = codeBlock($(section, '[data-code]')); + setCode(INITIAL_GLSL, INITIAL_HLSL, 'Generated ahead of time from the default formula; AngouriMath replaces it once it has loaded.'); + if (matchMedia('(min-width: 900px)').matches) $(section, '[data-code]').open = true; + + const waves = WAVES(); + const state = { + depth: 8, steep: 0.1, heading: Math.PI / 2, + playing: !matchMedia('(prefers-reduced-motion: reduce)').matches, yaw: 0, pitch: -0.13, + }; + + // ------------------------------------------------------------ WebGL + const gl = canvas.getContext('webgl2', { antialias: true }); + let sea = null, skyProg = null, seaVao = null, skyVao = null, indexCount = 0; + + function buildSea(fn) { + const next = linkProgram(gl, HEADER + fn + SEA_VS, HEADER + fn + SKY + SEA_FS, 'aGrid'); + if (sea) gl.deleteProgram(sea.program); + sea = next; + } + + if (gl) { + skyProg = linkProgram(gl, FULLSCREEN_VS, HEADER + SKY + SKY_FS); + skyVao = fullscreenTriangle(gl); + const verts = new Float32Array((GRID + 1) * (GRID + 1) * 2); + let p = 0; + for (let j = 0; j <= GRID; j++) + for (let i = 0; i <= GRID; i++) { verts[p++] = i / GRID * 2 - 1; verts[p++] = j / GRID * 2 - 1; } + const idx = new Uint32Array(GRID * GRID * 6); + let q = 0; + for (let j = 0; j < GRID; j++) + for (let i = 0; i < GRID; i++) { + const a = j * (GRID + 1) + i, b = a + 1, c = a + GRID + 1, d = c + 1; + idx[q++] = a; idx[q++] = c; idx[q++] = b; idx[q++] = b; idx[q++] = c; idx[q++] = d; + } + indexCount = idx.length; + seaVao = gl.createVertexArray(); + gl.bindVertexArray(seaVao); + gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer()); + gl.bufferData(gl.ARRAY_BUFFER, verts, gl.STATIC_DRAW); + gl.enableVertexAttribArray(0); + gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0); + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, gl.createBuffer()); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, idx, gl.STATIC_DRAW); + gl.bindVertexArray(null); + buildSea(INITIAL_GLSL); + } + + const norm = (v) => { const l = Math.hypot(...v); return v.map((x) => x / l); }; + const cross = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]; + const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; + + function camera(aspect) { + const eye = [0, 5.5, 0]; + const fwd = [Math.sin(state.yaw) * Math.cos(state.pitch), Math.sin(state.pitch), -Math.cos(state.yaw) * Math.cos(state.pitch)]; + const right = norm(cross(fwd, [0, 1, 0])), up = cross(right, fwd); + const f = 1 / Math.tan(FOV / 2), near = 0.1, far = 3000, nf = 1 / (near - far); + const view = [right[0], up[0], -fwd[0], 0, right[1], up[1], -fwd[1], 0, right[2], up[2], -fwd[2], 0, + -dot(right, eye), -dot(up, eye), dot(fwd, eye), 1]; + const proj = [f / aspect, 0, 0, 0, 0, f, 0, 0, 0, 0, (far + near) * nf, -1, 0, 0, 2 * far * near * nf, 0]; + const vp = new Float32Array(16); + for (let c = 0; c < 4; c++) + for (let r = 0; r < 4; r++) { + let s = 0; + for (let k = 0; k < 4; k++) s += proj[k * 4 + r] * view[c * 4 + k]; + vp[c * 4 + r] = s; + } + return { eye, fwd, right, up, vp, tan: [Math.tan(FOV / 2) * aspect, Math.tan(FOV / 2)] }; + } + + const amplitude = (w) => Math.min(state.steep * w.weight / w.k, 0.2 * state.depth); + function bodyColour() { + const t = Math.min(Math.max(Math.log(state.depth / 0.5) / Math.log(40 / 0.5), 0), 1); + const shallow = [0.10, 0.42, 0.42], deep = [0.02, 0.10, 0.16]; + return shallow.map((s, i) => s + (deep[i] - s) * t); + } + + const waveData = new Float32Array(4 * WAVE_COUNT), dirData = new Float32Array(4 * WAVE_COUNT); + const animation = loop((dt) => { + if (!gl) return; + if (state.playing) for (const w of waves) w.t += dt; + const [width, height] = fitCanvas(canvas); + gl.viewport(0, 0, width, height); + const cam = camera(width / height); + // The height the crest shading spans: random phases rarely line up, so not the sum of the + // amplitudes but a multiple of the RMS height, about the significant wave height. + let sumSquares = 0; + waves.forEach((w, i) => { + const a = amplitude(w), angle = state.heading + w.turn; + sumSquares += a * a; + waveData.set([a, w.k, w.t, 0], i * 4); + dirData.set([Math.cos(angle), Math.sin(angle), w.off[0], w.off[1]], i * 4); + }); + gl.disable(gl.DEPTH_TEST); + gl.useProgram(skyProg.program); + gl.uniform3fv(skyProg.loc.uSun, SUN); + gl.uniform3fv(skyProg.loc.uFwd, cam.fwd); + gl.uniform3fv(skyProg.loc.uRight, cam.right); + gl.uniform3fv(skyProg.loc.uUp, cam.up); + gl.uniform2fv(skyProg.loc.uTan, cam.tan); + gl.bindVertexArray(skyVao); + gl.drawArrays(gl.TRIANGLES, 0, 3); + gl.enable(gl.DEPTH_TEST); + gl.clear(gl.DEPTH_BUFFER_BIT); + const L = sea.loc; + gl.useProgram(sea.program); + gl.uniformMatrix4fv(L.uViewProj, false, cam.vp); + gl.uniform3fv(L.uCam, cam.eye); + gl.uniform3fv(L.uSun, SUN); + gl.uniform1f(L.uExtent, EXTENT); + gl.uniform1f(L.uDepth, state.depth); + gl.uniform1f(L.uMaxA, 2 * Math.sqrt(sumSquares)); + gl.uniform3fv(L.uBody, bodyColour()); + gl.uniform4fv(L.uWave, waveData); + gl.uniform4fv(L.uDirOff, dirData); + gl.bindVertexArray(seaVao); + gl.drawElements(gl.TRIANGLES, indexCount, gl.UNSIGNED_INT, 0); + }); + + // ------------------------------------------------------------ physics readout + + let amReady = false; + // Each wave keeps its phase when its frequency changes: t is rescaled so that omega t stays. + async function refreshOmegas() { + const ks = waves.map((w) => w.k); + let next; + try { + next = amReady ? await am.call('WavesJs', 'Omegas', [ks, state.depth]) : null; + } catch { next = null; } + next ??= ks.map((k) => Math.sqrt(9.81 * k * Math.tanh(k * state.depth))); + waves.forEach((w, i) => { + const o = next[i]; + if (Number.isFinite(w.omega) && w.omega > 0 && Number.isFinite(o) && o > 0) w.t *= w.omega / o; + w.omega = o ?? NaN; + }); + updateReadout(); + } + + const speed = (w) => { const c = w.omega / w.k; return Number.isFinite(c) ? `${c.toFixed(1)} m/s` : 'no speed'; }; + function updateReadout() { + const long = waves[0], short = waves[waves.length - 1]; + $(section, '[data-c-long]').textContent = speed(long); + $(section, '[data-c-short]').textContent = speed(short); + const lo = long.k * state.depth, hi = short.k * state.depth; + $(section, '[data-kh]').textContent = `${lo < 1 ? lo.toFixed(2) : lo.toFixed(1)} to ${hi < 10 ? hi.toFixed(1) : hi.toFixed(0)}`; + let regime; + if (hi < 0.3) regime = 'Shallow for every wave (k h < 0.3): all of them travel at √(g h).'; + else if (lo > Math.PI) regime = 'Deep for every wave (k h > π): the bottom no longer matters.'; + else if (lo < 0.3 && hi > Math.PI) regime = 'Shallow for the longest waves, deep for the shortest.'; + else regime = 'Between shallow and deep water for most of the waves.'; + $(section, '[data-regime]').textContent = regime; + } + + // ------------------------------------------------------------ AngouriMath + + const chip = $(section, '[data-chip]'); + let generation = 0; + async function generate(text) { + const mine = ++generation; + let r; + const t0 = performance.now(); + try { + r = await am.json('WavesJs', 'Generate', [text]); + } catch (e) { + if (mine !== generation) return; + setChip(chip, 'bad', 'AngouriMath stopped'); + $(section, '[data-phase]').textContent = e.message; + return; + } + if (mine !== generation) return; + $(section, '[data-timing]').textContent = `checked and generated in ${Math.round(performance.now() - t0)} ms`; + $(section, '[data-omega]').textContent = r.omega || '–'; + $(section, '[data-phase]').textContent = r.phase || '–'; + if (r.ok) { + try { + if (gl) buildSea(r.glsl); + setCode(r.glsl, r.hlsl, `Generated by AngouriMath in this tab from ω = ${text.trim()}`); + setChip(chip, 'ok', 'Units agree: shader generated'); + $(section, '[data-kept]').hidden = true; + refreshOmegas(); + } catch (e) { + setChip(chip, 'bad', 'The GPU did not accept the shader'); + $(section, '[data-phase]').textContent = String(e.message || e); + $(section, '[data-kept]').hidden = false; + } + } else { + if ((r.omega || '').startsWith('Could not read')) setChip(chip, 'warn', 'Not a formula yet'); + else if (r.kind === 'Undetermined') setChip(chip, 'warn', 'Units unknown'); + else if (r.kind === 'Inconsistent') setChip(chip, 'bad', 'Units disagree: rejected'); + else { setChip(chip, 'bad', 'No shader form'); $(section, '[data-phase]').textContent = r.reason || r.phase; } + $(section, '[data-kept]').hidden = false; + } + } + + // ------------------------------------------------------------ controls + + const input = $(section, '#waves-omega'), note = $(section, '[data-note]'); + const press = presets($(section, '.presets'), PRESETS, (p) => { + input.value = p.formula; + note.textContent = p.note; + press(p.label); + generate(p.formula); + }); + input.value = PRESETS[0].formula; + note.textContent = PRESETS[0].note; + press(PRESETS[0].label); + let debounce = 0; + input.addEventListener('input', () => { + press(null); + note.textContent = ''; + clearTimeout(debounce); + debounce = setTimeout(() => generate(input.value), 350); + }); + input.addEventListener('keydown', (e) => { if (e.key === 'Enter') { clearTimeout(debounce); generate(input.value); } }); + + const depth = $(section, '#waves-depth'), steep = $(section, '#waves-steep'), heading = $(section, '#waves-heading'); + const syncDepth = () => { + state.depth = 0.3 * Math.pow(200, +depth.value / 1000); + const h = state.depth; + $(section, '[data-depth-out]').textContent = h < 1 ? `${h.toFixed(2)} m` : h < 10 ? `${h.toFixed(1)} m` : `${h.toFixed(0)} m`; + refreshOmegas(); + }; + const syncSteep = () => { state.steep = +steep.value / 500; $(section, '[data-steep-out]').textContent = state.steep.toFixed(3); }; + const syncHeading = () => { state.heading = +heading.value * Math.PI / 180; $(section, '[data-heading-out]').textContent = `${heading.value}°`; }; + depth.addEventListener('input', syncDepth); + steep.addEventListener('input', syncSteep); + heading.addEventListener('input', syncHeading); + syncDepth(); syncSteep(); syncHeading(); + + const play = $(section, '[data-play]'); + const syncPlay = () => { play.textContent = state.playing ? 'Pause' : 'Play'; }; + play.addEventListener('click', () => { state.playing = !state.playing; syncPlay(); }); + syncPlay(); + + let drag = null; + canvas.addEventListener('pointerdown', (e) => { drag = { x: e.clientX, y: e.clientY }; canvas.setPointerCapture(e.pointerId); }); + canvas.addEventListener('pointermove', (e) => { + if (!drag) return; + state.yaw += (e.clientX - drag.x) * 0.004; + state.pitch = Math.min(0.15, Math.max(-0.75, state.pitch - (e.clientY - drag.y) * 0.004)); + drag = { x: e.clientX, y: e.clientY }; + }); + canvas.addEventListener('pointerup', () => { drag = null; }); + canvas.addEventListener('pointercancel', () => { drag = null; }); + + am.call('WavesJs', 'Groups').then((groups) => { + amReady = true; + $(section, '[data-groups]').textContent = groups.join(', '); + generate(input.value); + }).catch(() => {}); + + if (!gl) $(section, '[data-regime]').textContent = 'This browser has no WebGL2, so the sea cannot be drawn. AngouriMath still checks the formulas.'; + return { show: () => animation.start(), hide: () => animation.stop() }; +} diff --git a/src/content/_templates/top.html b/src/content/_templates/top.html index 3f86a7e0ad..9ba4c6b951 100644 --- a/src/content/_templates/top.html +++ b/src/content/_templates/top.html @@ -48,7 +48,7 @@

    Table of contents

  1. Almanac
  2. Research
  3. What's new
  4. -
  5. Try online
  6. +
  7. Try it live
  8. GitHub
  9. Report a bug
  10. Contacts
  11. @@ -75,7 +75,7 @@

    AngouriMath

    Almanac Research What's new -Try +Try it live Use Angouri.org GitHub diff --git a/src/content/demo/index.html b/src/content/demo/index.html index ed7adba154..17aeac3b44 100644 --- a/src/content/demo/index.html +++ b/src/content/demo/index.html @@ -1,8 +1,13 @@  -

    Try AngouriMath online

    +

    Try AngouriMath in C#


    - If you want to try Jupyter online, try here. + To try the library without writing code, open AngouriMath Live: the + library itself, running in your browser as WebAssembly, behind nine pages of formulas to edit. +

    +

    + This page is for the C# side: samples you can edit and run below, and Jupyter notebooks online + here.

    diff --git a/src/content/index.html b/src/content/index.html index 8ec08d8e6d..d6807f12e5 100644 --- a/src/content/index.html +++ b/src/content/index.html @@ -22,6 +22,8 @@

    What is Angour


    diff --git a/styles.css b/styles.css index 41bc7edf4a..467fc16139 100644 --- a/styles.css +++ b/styles.css @@ -251,3 +251,22 @@ a { .whatsnew-page li { margin-top: 1vh; } + +/* The way into AngouriMath Live, the library in the browser: a button rather than a link, in the + site's magenta, wherever it appears. Its colours hold in both themes. */ +a.try-live, +.nav-left ul li a.try-live { + display: inline-block; + padding: 0.35em 1em; + border-radius: 999px; + background-color: #BB0099; + color: white; + font-weight: bold; + text-decoration: none; +} + +a.try-live:hover, +.nav-left ul li a.try-live:hover { + background-color: #D4007A; + color: white; +}