Skip to content

Commit 7741d8a

Browse files
amcli info describes an expression (#1661)
amcli info EXPR prints the expression's variables, the derivative and the roots over each, and its stationary points, each classified by the second derivative test. A point that is not real says so. For one variable the test reads the second derivative, and for several it reads the Hessian's leading principal minors (Sylvester's criterion): all positive is a minimum, alternating from negative a maximum, another nonzero determinant a saddle point, and a zero determinant decides nothing. It is the command ASC-Community/AngouriMathCLI#4 proposed for the standalone CLI, written anew here, since that repository is GPL-3.0 and this one MIT. Part of #1649. Claude-Session: https://claude.ai/code/session_012sonx8iAspMiwRwokT1Ura Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
1 parent 3897435 commit 7741d8a

3 files changed

Lines changed: 114 additions & 4 deletions

File tree

‎Sources/Terminal/AngouriMath.Terminal.Lib/OneShot.fs‎

Lines changed: 85 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,14 +26,15 @@ amcli diff VAR EXPR differentiates over VAR
2626
amcli solve VAR STATEMENT solves over VAR, one root per line when there are finitely many
2727
amcli sub VAR VALUE EXPR substitutes VALUE for VAR
2828
amcli latex EXPR writes EXPR as LaTeX
29+
amcli info EXPR its variables, derivatives, roots and stationary points
2930
amcli help prints this
3031
3132
An argument written as _ is read from stdin, and so is one that is left out:
3233
echo "1 + x^2" | amcli diff x
3334
"""
3435

3536
/// The names <c>run</c> answers. Anything else as a first argument is a usage error.
36-
let commands = set [ "eval"; "simp"; "fsimp"; "diff"; "solve"; "sub"; "latex"; "help"; "-h"; "--help" ]
37+
let commands = set [ "eval"; "simp"; "fsimp"; "diff"; "solve"; "sub"; "latex"; "info"; "help"; "-h"; "--help" ]
3738

3839
/// The arguments still to read, falling back to a line of stdin where one is missing or is <c>_</c>.
3940
type private Arguments(given: string list, input: TextReader) =
@@ -47,6 +48,85 @@ type private Arguments(given: string list, input: TextReader) =
4748
if head = "_" then Option.ofObj (input.ReadLine()) else Some head
4849
| [] -> Option.ofObj (input.ReadLine())
4950

51+
/// <summary>
52+
/// A real number's sign, where <paramref name="value"/> evaluates to one; otherwise None.
53+
/// </summary>
54+
let private signOf (value: Entity) =
55+
match value.Evaled with
56+
| :? Entity.Number.Real as real -> Some (if real.IsZero then 0 elif real.IsNegative then -1 else 1)
57+
| _ -> None
58+
59+
/// <summary>Whether <paramref name="value"/> is a number off the real line.</summary>
60+
let private isNotReal (value: Entity) =
61+
match value.Evaled with
62+
| :? Entity.Number.Real -> false
63+
| :? Entity.Number.Complex -> true
64+
| _ -> false
65+
66+
/// <summary>
67+
/// What a stationary point is, by the second derivative test: with the Hessian's leading principal
68+
/// minors <c>D1 ... Dn</c>, all positive is a minimum, <c>(-1)^k Dk</c> all positive a maximum, and
69+
/// any other nonzero determinant a saddle point (Sylvester's criterion). A zero determinant decides
70+
/// nothing, and a minor that is not a real number leaves the point unclassified.
71+
/// </summary>
72+
let private kindOfStationaryPoint (hessian: int -> int -> Entity) (size: int) =
73+
let minors =
74+
[ for k in 1 .. size ->
75+
if k = 1 then hessian 0 0
76+
else (MathS.Matrix(k, k, fun row column -> hessian row column)).Determinant |> Option.ofObj |> Option.defaultValue MathS.NaN ]
77+
|> List.map signOf
78+
if minors |> List.exists Option.isNone then "not classified: its second derivatives there are not real numbers"
79+
else
80+
let signs = minors |> List.map Option.get
81+
if List.last signs = 0 then "a degenerate point, which the second derivative test does not decide"
82+
elif signs |> List.forall (fun sign -> sign > 0) then "a minimum"
83+
elif signs |> List.mapi (fun k sign -> if k % 2 = 0 then -sign else sign) |> List.forall (fun sign -> sign > 0) then "a maximum"
84+
else "a saddle point"
85+
86+
/// <summary>
87+
/// The lines <c>amcli info</c> prints: the variables, the derivative and the roots over each, and
88+
/// the stationary points, each classified by the second derivative test.
89+
/// </summary>
90+
let private describe (expression: Entity) =
91+
let variables = expression.Vars |> Seq.toList
92+
let names = String.Join(", ", variables)
93+
[ yield $"variables: {names}"
94+
for v in variables do
95+
yield $"derivative over {v}: {expression.Differentiate(v).Simplify().Stringize()}"
96+
for v in variables do
97+
yield $"roots over {v}: {expression.Equalizes(Entity.Number.Integer.Zero).Solve(v).Simplify().Stringize()}"
98+
match variables with
99+
| [] -> ()
100+
| [ v ] ->
101+
let first = expression.Differentiate(v).Simplify()
102+
let second = first.Differentiate(v).Simplify()
103+
match first.Equalizes(Entity.Number.Integer.Zero).Solve(v) with
104+
| :? Entity.Set.FiniteSet as points ->
105+
if points.Count = 0 then yield "stationary points: none"
106+
for point in points do
107+
if isNotReal point then
108+
yield $"stationary point {v} = {point.Stringize()}: not real"
109+
else
110+
let at (e: Entity) = e.Substitute(v, point)
111+
let kind = kindOfStationaryPoint (fun _ _ -> at second) 1
112+
yield $"stationary point {v} = {point.Stringize()}: {kind}, value {(at expression).Simplify().Stringize()}"
113+
| points -> yield $"stationary points: {points.Stringize()}"
114+
| _ ->
115+
let gradient = [ for v in variables -> expression.Differentiate(v).Simplify() ]
116+
match MathS.Equations(gradient).Solve(variables |> List.toArray) with
117+
| Null -> yield "stationary points: not found"
118+
| NonNull solutions ->
119+
for row in 0 .. solutions.RowCount - 1 do
120+
let at (e: Entity) =
121+
variables |> List.indexed |> List.fold (fun (acc: Entity) (i, v) -> acc.Substitute(v, solutions.[row, i])) e
122+
let hessian i j = at (expression.Differentiate(variables.[i]).Differentiate(variables.[j]))
123+
let point = String.Join(", ", [ for i in 0 .. variables.Length - 1 -> solutions.[row, i].Stringize() ])
124+
if [ for i in 0 .. variables.Length - 1 -> solutions.[row, i] ] |> List.exists isNotReal then
125+
yield $"stationary point ({names}) = ({point}): not real"
126+
else
127+
let kind = kindOfStationaryPoint hessian variables.Length
128+
yield $"stationary point ({names}) = ({point}): {kind}, value {(at expression).Simplify().Stringize()}" ]
129+
50130
/// What a command printed, one line each.
51131
let private answer (command: string) (next: unit -> string option) : Result<string list, string> =
52132
let expression () = next () |> Option.map MathS.FromString
@@ -99,6 +179,10 @@ let private answer (command: string) (next: unit -> string option) : Result<stri
99179
match expression () with
100180
| Some e -> Ok [ e.Latexize() ]
101181
| None -> missing
182+
| "info" ->
183+
match expression () with
184+
| Some e -> Ok (describe e)
185+
| None -> missing
102186
| _ -> Ok (usage.TrimEnd().Split('\n') |> List.ofArray)
103187

104188
/// <summary>

‎Sources/Terminal/readme.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,10 @@ $ echo "1 + x^2" | amcli diff x
4242
2 * x
4343
```
4444

45-
The commands are `eval`, `simp`, `fsimp`, `diff`, `solve`, `sub` and `latex`, and `amcli help`
46-
says what each takes. An argument written as `_`, or left out, is read from stdin. The exit code
45+
The commands are `eval`, `simp`, `fsimp`, `diff`, `solve`, `sub`, `latex` and `info`, and
46+
`amcli help` says what each takes. `info` describes an expression: its variables, the derivative
47+
and the roots over each, and its stationary points, each classified by the second derivative
48+
test. An argument written as `_`, or left out, is read from stdin. The exit code
4749
is 0 for an answer, 1 when the input does not parse or cannot be answered, and 2 for a command
4850
that does not exist or is missing an argument. These are the commands of the earlier standalone
4951
command-line tool, with the same names and argument order.

‎Sources/Tests/TerminalUnitTests/OneShotTest.fs‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,5 +91,29 @@ let ``input that does not parse fails, and says why`` () =
9191
let ``help lists every command`` () =
9292
let code, printed, _ = run [ "help" ] ""
9393
Assert.Equal(0, code)
94-
for command in [ "eval"; "simp"; "fsimp"; "diff"; "solve"; "sub"; "latex" ] do
94+
for command in [ "eval"; "simp"; "fsimp"; "diff"; "solve"; "sub"; "latex"; "info" ] do
9595
Assert.Contains($"amcli {command} ", printed)
96+
97+
/// What info says about an expression's stationary points, by the second derivative test.
98+
[<Theory>]
99+
[<InlineData("x^2 - 2*x", "stationary point x = 1: a minimum, value -1")>]
100+
[<InlineData("2*x - x^2", "stationary point x = 1: a maximum, value 1")>]
101+
[<InlineData("x^3", "stationary point x = 0: a degenerate point, which the second derivative test does not decide, value 0")>]
102+
[<InlineData("x^2 + y^2", "stationary point (x, y) = (0, 0): a minimum, value 0")>]
103+
[<InlineData("-x^2 - y^2", "stationary point (x, y) = (0, 0): a maximum, value 0")>]
104+
[<InlineData("x^2 - y^2", "stationary point (x, y) = (0, 0): a saddle point, value 0")>]
105+
[<InlineData("x^3 + x", "stationary point x = sqrt(-1/3): not real")>]
106+
let ``info classifies each stationary point`` (expression: string) (expected: string) =
107+
let code, printed, error = run [ "info"; expression ] ""
108+
Assert.Equal("", error)
109+
Assert.Equal(0, code)
110+
Assert.Contains(expected, printed.Split('\n'))
111+
112+
[<Fact>]
113+
let ``info names the variables and gives the derivative and the roots over each`` () =
114+
let code, printed, _ = run [ "info"; "x^2 - 4" ] ""
115+
Assert.Equal(0, code)
116+
let lines = printed.Split('\n')
117+
Assert.Contains("variables: x", lines)
118+
Assert.Contains("derivative over x: 2 * x", lines)
119+
Assert.Contains(lines, fun line -> line.StartsWith("roots over x: ") && line.Contains("-2") && line.Contains("2"))

0 commit comments

Comments
 (0)