Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions Sources/AngouriMath/Convenience/MathS.cs
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,55 @@ public static Integer GreatestCommonDivisor(Integer a, Integer b)
/// </example>
public static Set SolveEquation(Entity equation, Variable var) => EquationSolver.Solve(equation, var);

/// <summary>
/// Solves a system of equations written as one statement, a conjunction of equations,
/// jointly for several variables, as <see cref="Equations(Entity[])"/> solves one written
/// as a list.
/// </summary>
/// <param name="system">
/// Equations joined by <c>and</c>, nested or not: <c>x + y = 3 and x - y = 1</c>. An
/// equation <c>a = b</c> is read as <c>a - b = 0</c>, and a chain <c>a = b = c</c> is the
/// conjunction <c>a = b and b = c</c>. One equation is a system of one, and an expression
/// that is not a statement is read as equal to zero, as <see cref="SolveEquation"/> reads one.
/// </param>
/// <param name="variables">
/// The unknowns, in the order of the answer's columns, as many as there are equations or
/// not, as <see cref="EquationSystem.Solve(Variable[])"/> takes them.
/// </param>
/// <returns>
/// What <see cref="EquationSystem.Solve(Variable[])"/> answers for the equations: a matrix
/// with a row for each solution and a column for each variable, a variable the system
/// leaves free becoming a parameter. <see langword="null"/> where no solution was found,
/// which includes a system that has none, as <c>x + y = 1 and x + y = 2</c>, and one the
/// solver could not settle. Also <see langword="null"/> where a conjunct is not an
/// equation -- an inequality, an <c>in</c>, an <c>or</c>, a <c>not</c> or a boolean --
/// since solving the others alone would answer a different question; solve such a
/// statement for one variable at a time with <see cref="Entity.Solve(Variable)"/>.
/// </returns>
/// <remarks>
/// <see cref="Entity.Solve(Variable)"/> on the same statement solves it for one variable,
/// with the others as parameters: <c>x + y = 3 and x - y = 1</c> for <c>x</c> is
/// <c>{ 3 - y } ∩ { 1 + y }</c>, the values of <c>x</c> for each <c>y</c>. This is the
/// question for all of them at once, and answers the point <c>(2, 1)</c>.
/// https://github.com/asc-community/AngouriMath/issues/2450
/// </remarks>
/// <exception cref="NotSufficientlySupportedException">
/// As <see cref="EquationSystem.Solve(Variable[])"/>: the work the call may spend ran out
/// before the system was solved, which is "not settled", not "no solution".
/// </exception>
/// <example>
/// <code>
/// var solutions = MathS.SolveSystem("x^2 + y^2 = 25 and x - y = 1", "x", "y");
/// Console.WriteLine(solutions);
/// </code>
/// Prints
/// <code>
/// [[-3, -4], [4, 3]]
/// </code>
/// </example>
public static Matrix? SolveSystem(Entity system, params Variable[] variables)
=> EquationSystem.EquationsOf(system, out _) is { } equations ? new EquationSystem(equations).Solve(variables) : null;

/// <summary>
/// Solves a first-order linear ordinary differential equation
/// <a href="https://en.wikipedia.org/wiki/Linear_differential_equation"/> by its
Expand Down
40 changes: 40 additions & 0 deletions Sources/AngouriMath/Core/EquationSystem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,46 @@ public sealed class EquationSystem : ILatexizeable
private static Entity AsAnExpressionEqualToZero(Entity equation)
=> equation is Equalsf(var left, var right) ? left - right : equation;

/// <summary>
/// The equations of <paramref name="system"/>, each an expression equal to zero, where it
/// is a conjunction of equations -- nested or not, and one equation is a conjunction of
/// one -- or an expression, which is read as equal to zero. <see langword="null"/>, with
/// the first conjunct that is not an equation in <paramref name="notAnEquation"/>, where
/// any conjunct is something else: an inequality, a membership, a disjunction, a
/// negation or a boolean. Leaving one out would answer a different question.
/// </summary>
/// <remarks>
/// An equality whose side is itself a statement, <c>(x = 1) = (y = 2)</c>, is an
/// equivalence of statements rather than an equation in numbers, and is not one either.
/// https://github.com/asc-community/AngouriMath/issues/2450
/// </remarks>
internal static List<Entity>? EquationsOf(Entity system, out Entity? notAnEquation)
{
notAnEquation = null;
if (system is not Statement)
return new List<Entity> { system };
var equations = new List<Entity>();
var pending = new Stack<Entity>();
pending.Push(system);
while (pending.Count > 0)
{
switch (pending.Pop())
{
case Andf(var left, var right):
pending.Push(right);
pending.Push(left);
break;
case Equalsf(var left, var right) when left is not Statement && right is not Statement:
equations.Add(left - right);
break;
case var other:
notAnEquation = other;
return null;
}
}
return equations;
}

/// <summary>
/// Solves a system of equations, if possible.
/// </summary>
Expand Down
10 changes: 8 additions & 2 deletions Sources/AngouriMath/Core/Operations/Catalogue.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//
//
// Copyright (c) 2019-2026 Angouri.
// AngouriMath is licensed under MIT.
// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.
Expand Down Expand Up @@ -102,6 +102,12 @@ internal static class Catalogue
static (equations, variables) => MathS.Equations(equations).Solve([.. variables]),
new Parameter("variables", "The variables to solve for, in the order of the answer's columns."));

/// <summary><see cref="MathS.SolveSystem(Entity, Variable[])"/>.</summary>
public static Query<Func<Entity, IReadOnlyList<Variable>, Matrix?>> SolveConjunction { get; } = new(
"solve_conjunction", "Solves a conjunction of equations jointly for several variables, as solve_system solves them listed, and declines one with a conjunct that is not an equation.",
static (system, variables) => MathS.SolveSystem(system, [.. variables]),
new Parameter("variables", "The variables to solve for, in the order of the answer's columns."));

/// <summary><see cref="Entity.Evaled"/>.</summary>
public static Query<Func<Entity, Entity>> Evaluate { get; } = new(
"evaluate", "Evaluates as far as it goes: to a number, a boolean or a set where it can, and as an expression where it cannot.",
Expand Down Expand Up @@ -254,7 +260,7 @@ internal static class Catalogue
public static IReadOnlyList<Operation> All { get; } =
[
Simplify, Normalize, Expand, Factorize, Differentiate, Integrate, Limit, Substitute,
Solve, SolveSystem, Evaluate, EvaluateNumerically, Variables, Alternatives, Latex, Sympy, TruthTable, SatisfyingAssignments, Series, AreEqual,
Solve, SolveSystem, SolveConjunction, Evaluate, EvaluateNumerically, Variables, Alternatives, Latex, Sympy, TruthTable, SatisfyingAssignments, Series, AreEqual,
ToBase, FromBase,
Determinant, Inverse, Transpose, Rank, ReducedRowEchelonForm, Trace, TensorProduct,
PrimeFactorization, Totient, GreatestCommonDivisor, DivisorCount, IsPrime,
Expand Down
45 changes: 37 additions & 8 deletions Sources/MCP/AngouriMath.Mcp/Tools.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//
//
// Copyright (c) 2019-2026 Angouri.
// AngouriMath is licensed under MIT.
// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.
Expand Down Expand Up @@ -93,7 +93,7 @@ private static JsonObject Schema(JsonObject props, params string[] required)
["am_limit"] = [Catalogue.Limit],
["am_evaluate"] = [Catalogue.EvaluateNumerically],
["am_truth_table"] = [Catalogue.TruthTable, Catalogue.SatisfyingAssignments],
["am_solve_system"] = [Catalogue.SolveSystem],
["am_solve_system"] = [Catalogue.SolveSystem, Catalogue.SolveConjunction],
["am_represent"] = [Catalogue.ToBase, Catalogue.FromBase],
["am_matrix"] = [Catalogue.Determinant, Catalogue.Inverse, Catalogue.Transpose, Catalogue.Rank,
Catalogue.ReducedRowEchelonForm, Catalogue.Trace, Catalogue.TensorProduct],
Expand Down Expand Up @@ -327,23 +327,30 @@ private static JsonObject[] All() =>

Tool("am_solve_system",
"Solve a system of simultaneous equations for several variables. Returns one row " +
"per solution. Note: nonlinear systems may return no solution even when one " +
"per solution. Give the system either as a list of equations or as one statement " +
"joining them with 'and'. Note: nonlinear systems may return no solution even when one " +
"exists (a known library limitation).",
Schema(new JsonObject
{
["equations"] = new JsonObject
{
["type"] = "array",
["items"] = new JsonObject { ["type"] = "string" },
["description"] = "Equations, e.g. ['x + y = 3', 'x - y = 1'].",
["description"] = "Equations, e.g. ['x + y = 3', 'x - y = 1']. Give this or 'statement'.",
},
["statement"] = new JsonObject
{
["type"] = "string",
["description"] = "The system as one conjunction of equations, e.g. 'x + y = 3 and x - y = 1'. " +
"Declined where a conjunct is not an equation (an inequality, 'in', 'or', 'not'). Give this or 'equations'.",
},
["variables"] = new JsonObject
{
["type"] = "array",
["items"] = new JsonObject { ["type"] = "string" },
["description"] = "Variables to solve for, e.g. ['x','y'].",
},
}, "equations", "variables")),
}, "variables")),

Tool("am_check_steps",
"Check a chain of working step by step and report WHICH step broke. Use this to " +
Expand Down Expand Up @@ -1386,8 +1393,10 @@ private static JsonObject TruthTable(JsonObject args)
private static JsonObject SolveSystem(JsonObject args)
{
var equations = A(args, "equations");
var statement = S(args, "statement");
var variables = A(args, "variables");
if (equations.Count == 0) return Fail("'equations' must not be empty");
if (statement is not null && equations.Count > 0) return Fail("give 'equations' or 'statement', not both");
if (statement is null && equations.Count == 0) return Fail("'equations' must not be empty");
if (variables.Count == 0) return Fail("'variables' must not be empty");

var parsed = new List<Entity>();
Expand All @@ -1402,8 +1411,28 @@ private static JsonObject SolveSystem(JsonObject args)
warnings.AddRange(w);
}

return FromOutcome(Guard.Run(() =>
Catalogue.SolveSystem.Ask(parsed, [.. variables.Select(Var)])), matrix =>
Entity? system = null;
if (statement is not null)
{
if (!TryParse(statement, "statement", false, out var e, out var w, out var error))
return error!;
// A conjunct that is not an equation is declined by the library as well; naming it
// here is what tells the caller why, where the library can only say null.
if (EquationSystem.EquationsOf(e, out var notAnEquation) is null)
return new JsonObject
{
["status"] = "declined",
["note"] = $"'{notAnEquation!.Stringize()}' is not an equation, and solving the other " +
"conjuncts without it would answer a different question. Solve the statement for one " +
"variable with am_solve instead.",
};
system = e;
warnings.AddRange(w);
}

return FromOutcome(Guard.Run(() => system is not null
? Catalogue.SolveConjunction.Ask(system, [.. variables.Select(Var)])
: Catalogue.SolveSystem.Ask(parsed, [.. variables.Select(Var)])), matrix =>
{
var order = new JsonArray();
foreach (var v in variables) order.Add(v);
Expand Down
2 changes: 1 addition & 1 deletion Sources/MCP/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ echo '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}' | amcli mcp
| `am_are_equal` | `equal` only with a proof, `not_equal` only with a witness point, else `unknown`; never decided by sampling alone. Bounded in steps |
| `am_check_steps` | checks a chain of working and names the step that broke |
| `am_truth_table` | the table and the satisfying assignments |
| `am_solve_system` | takes `x + y = 3` as well as `x + y - 3` |
| `am_solve_system` | takes `x + y = 3` as well as `x + y - 3`, and the system as a list or as one statement, `x + y = 3 and x - y = 1`; a conjunct that is not an equation is declined and named |
| `am_domain_check` | domain conditions, structural hazards, and where it stops being real |
| `am_represent` | encodings: bases 2–36, Q-format fixed point, IEEE 754 bits, polar form |
| `am_matrix` | determinant, inverse, transpose, rank, RREF, trace, multiply, tensor product, power |
Expand Down
2 changes: 1 addition & 1 deletion Sources/Terminal/AngouriMath.Terminal.Lib/OneShot.fs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ let ownCommands =
/// the question of #1019 item 16; an entry added to the catalogue joins this list or a command.
/// </summary>
let notOffered =
set [ "expand"; "factorize"; "integrate"; "limit"; "solve_system"; "evaluate_numerically"; "variables"
set [ "expand"; "factorize"; "integrate"; "limit"; "solve_system"; "solve_conjunction"; "evaluate_numerically"; "variables"
"alternatives"; "sympy"; "truth_table"; "satisfying_assignments"; "series"; "to_base"; "from_base"
"determinant"; "inverse"; "transpose"; "rank"; "reduced_row_echelon_form"; "trace"; "tensor_product"
"prime_factorization"; "totient"; "greatest_common_divisor"; "divisor_count"; "is_prime"; "are_equal" ]
Expand Down
24 changes: 23 additions & 1 deletion Sources/Tests/McpUnitTests/ToolsTest.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//
//
// Copyright (c) 2019-2026 Angouri.
// AngouriMath is licensed under MIT.
// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.
Expand Down Expand Up @@ -223,6 +223,28 @@ public void ASystemWrittenAsEqualitiesIsSolved()
Assert.Equal("2 1", string.Join(" ", answer.Field("solutions").Split('\n')[1].Split(' ', StringSplitOptions.RemoveEmptyEntries)));
}

// https://github.com/asc-community/AngouriMath/issues/2450
[Fact]
public void ASystemWrittenAsOneConjunctionIsSolved()
{
var answer = Mcp.Call("am_solve_system", """{"statement":"x + y = 3 and x - y = 1","variables":["x","y"]}""");
Assert.Equal(1, answer["solution_count"]!.GetValue<int>());
Assert.Equal("2 1", string.Join(" ", answer.Field("solutions").Split('\n')[1].Split(' ', StringSplitOptions.RemoveEmptyEntries)));
}

[Fact]
public void AConjunctThatIsNotAnEquationIsNamedAndDeclined()
{
var answer = Mcp.Call("am_solve_system", """{"statement":"x + y = 3 and x > 0","variables":["x","y"]}""");
Assert.Equal("declined", answer.Field("status"));
Assert.Contains("x > 0", answer.Field("note"));
}

[Fact]
public void ASystemIsGivenAsAListOrAsAStatementNotBoth() =>
Assert.Equal("failed", Mcp.Call("am_solve_system",
"""{"equations":["x + y = 3"],"statement":"x - y = 1","variables":["x","y"]}""").Field("status"));

[Fact]
public void ToSympyWritesAProgram() =>
Assert.Contains("sympy", Mcp.Call("am_to_sympy", """{"expression":"sin(x)/x"}""").Field("sympy"));
Expand Down
1 change: 1 addition & 0 deletions Sources/Tests/UnitTests/Common/PublicApi.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3779,6 +3779,7 @@ AngouriMath.MathS.Sin(AngouriMath.Entity) : AngouriMath.Entity
AngouriMath.MathS.SolveBooleanTable(AngouriMath.Entity, AngouriMath.Entity+Variable[]) : AngouriMath.Entity+Matrix
AngouriMath.MathS.SolveEquation(AngouriMath.Entity, AngouriMath.Entity+Variable) : AngouriMath.Entity+Set
AngouriMath.MathS.SolveOde(AngouriMath.Entity, AngouriMath.Entity+Variable, AngouriMath.Entity+Variable) : AngouriMath.Entity
AngouriMath.MathS.SolveSystem(AngouriMath.Entity, AngouriMath.Entity+Variable[]) : AngouriMath.Entity+Matrix
AngouriMath.MathS.Sqr(AngouriMath.Entity) : AngouriMath.Entity
AngouriMath.MathS.Sqrt(AngouriMath.Entity) : AngouriMath.Entity
AngouriMath.MathS.Sum(AngouriMath.Entity, AngouriMath.Entity, AngouriMath.Entity) : AngouriMath.Entity
Expand Down
Loading
Loading