Skip to content

Commit b8a6a6f

Browse files
A quantifier, a subset and a cardinality over a finite set compile (#2234)
forall, exists, exists!, subset and card were refused by both compilers. Over a finite set the set is known when the expression is compiled, so each is a statement or a number about its members. CompiledMembership writes each one out before either compiler sees it: - forall and exists become the conjunction and the disjunction of the body at each member. Over the empty set they are True and False. - exists! becomes exactly one of them, as the disjunction over i of P_i and not P_j for every j other than i, by Kleene's connectives. - A finite set is a subset where each member is a member of the other set, by the membership rewrite of #2223. - card is the number of distinct values among the members. Each member counts, as an Iverson bracket, where it equals none before it, so the count has no value where an equality has none. Each is capped at 64 members, past which the cardinality and exists! grow with the square of the count, and is left as written there. Over any other set it is left as written too, and neither compiler compiles it. At a NaN argument the compiled value is undecided, or the vacuous truth of a quantifier over the empty set. Evaluation differs there for two reasons. A finite set drops a member whose value is NaN, so { NaN } is { } and card({ 1, NaN }) is 1. And a NaN anywhere in a quantifier's body makes the quantifier NaN. Undecided answers nothing wrong, and the vacuous truth is the mathematics, so the difference is pinned by its own test rather than mirrored. FiniteSetStatementCompilationTest compares both compilers with evaluation at 12 points, among them i, 1 + i and the infinities: - nine statements, among them nested quantifiers and quantifiers over the empty set; - three cardinalities; - the NaN cases; - four refusals over sets that are not finite. Part of #2195. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
1 parent fba9096 commit b8a6a6f

4 files changed

Lines changed: 194 additions & 2 deletions

File tree

‎BREAKING-CHANGES.md‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -388,6 +388,26 @@ truth value at any other ([#2195](https://github.com/asc-community/AngouriMath/i
388388
| `"x in [0; 1]".ToEntity().Compile("x").Call(0.5)` | `UncompilableNodeException` | `(1, 0)` |
389389
| `"3 divides x".ToEntity().Compile("x").Call(6)` | `UncompilableNodeException` | `(1, 0)` |
390390

391+
### A quantifier, a subset and a cardinality over a finite set compile
392+
393+
**Not silent: what was refused is compiled.** A quantifier, a subset and a cardinality were refused by both
394+
compilers with `UncompilableNodeException`. Over a finite set, of at most 64 members, each now compiles to what
395+
evaluation gives:
396+
- `forall` and `exists` are the conjunction and the disjunction of the body at each member, and `exists!` is
397+
exactly one of them, by Kleene's connectives;
398+
- a finite set is a subset where each of its members is a member of the other set;
399+
- a cardinality is the number of distinct values among the members.
400+
401+
Over any other set each is refused as before. At a `NaN` argument the compiled value is undecided, or the vacuous
402+
truth of a quantifier over the empty set, where evaluation drops a `NaN` member from a finite set
403+
([#2195](https://github.com/asc-community/AngouriMath/issues/2195)).
404+
405+
| Input | Was (2.6.0) | Now |
406+
|---|---|---|
407+
| `"forall t in { 1, 2, 3 } : t < x".ToEntity().Compile("x").Call(4)` | `UncompilableNodeException` | `(1, 0)` |
408+
| `"{ x } subset [0; 3]".ToEntity().Compile<double, bool>("x")(0.5)` | `UncompilableNodeException` | `True` |
409+
| `"card({ 1, x })".ToEntity().Compile("x").Call(1)` | `UncompilableNodeException` | `(1, 0)` |
410+
391411
### A congruence compiles
392412

393413
**Not silent: what was refused is compiled.** `a = b (mod n)` was refused by both compilers with

‎Sources/.editorconfig‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -917,6 +917,9 @@ file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed
917917
[Tests/UnitTests/Common/StatementInANumericPositionTest.cs]
918918
file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed under MIT.\nDetails: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.\nWebsite: https://am.angouri.org.\n
919919

920+
[Tests/UnitTests/Common/FiniteSetStatementCompilationTest.cs]
921+
file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed under MIT.\nDetails: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.\nWebsite: https://am.angouri.org.\n
922+
920923
[Tests/UnitTests/Convenience/EulerGammaTest.cs]
921924
file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed under MIT.\nDetails: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.\nWebsite: https://am.angouri.org.\n
922925

‎Sources/AngouriMath/Functions/Compilation/CompiledMembership.cs‎

Lines changed: 56 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,64 @@ namespace AngouriMath.Core.Compilation
2525
internal static class CompiledMembership
2626
{
2727
internal static Entity Rewritten(Entity expression)
28-
=> expression.Nodes.Any(node => node is Inf)
29-
? expression.Replace(node => node is Inf(var element, var set) && Statement(element, set) is { } statement ? statement : node)
28+
=> expression.Nodes.Any(node => node is Inf or Subsetf or Cardf or Quantifier)
29+
? expression.Replace(Rewrite)
3030
: expression;
3131

32+
// Past this many members a statement over a finite set is left as written: the cardinality and the
33+
// unique existence grow with the square of the count.
34+
private const int LargestExpanded = 64;
35+
36+
// A subset, a cardinality and a quantifier over a finite set are statements about its members, as evaluation
37+
// decides them, and any other is left as written, which neither compiler compiles.
38+
// https://github.com/asc-community/AngouriMath/issues/2195
39+
private static Entity Rewrite(Entity node) => node switch
40+
{
41+
Inf(var element, var set) => Statement(element, set) ?? node,
42+
Subsetf(FiniteSet sub, var super) when sub.Count <= LargestExpanded
43+
=> sub.Select(member => Statement(member, super)).ToList() is var each && each.All(statement => statement is not null)
44+
? each.Aggregate(Boolean.True as Entity, (all, statement) => all & statement!)
45+
: node,
46+
Cardf(FiniteSet set) when set.Count <= LargestExpanded => Cardinality(set.ToList()),
47+
Forallf(var variable, FiniteSet over, var body) when over.Count <= LargestExpanded
48+
=> over.Aggregate(Boolean.True as Entity, (all, member) => all & body.Substitute(variable, member)),
49+
Existsf(var variable, FiniteSet over, var body) when over.Count <= LargestExpanded
50+
=> over.Aggregate(Boolean.False as Entity, (any, member) => any | body.Substitute(variable, member)),
51+
ExistsUniquef(var variable, FiniteSet over, var body) when over.Count <= LargestExpanded
52+
=> ExactlyOne(over.Select(member => body.Substitute(variable, member)).ToList()),
53+
_ => node
54+
};
55+
56+
// The number of distinct values among the members: each counts where it equals none before it, and the
57+
// count has no value where an equality has none.
58+
private static Entity Cardinality(System.Collections.Generic.List<Entity> members)
59+
{
60+
Entity count = Number.Integer.Zero;
61+
for (var i = 0; i < members.Count; i++)
62+
{
63+
Entity unseen = Boolean.True;
64+
for (var j = 0; j < i; j++)
65+
unseen &= !members[i].Equalizes(members[j]);
66+
count += new Iversonf(unseen);
67+
}
68+
return count;
69+
}
70+
71+
// Exactly one of the statements holds, by Kleene's connectives.
72+
private static Entity ExactlyOne(System.Collections.Generic.List<Entity> statements)
73+
{
74+
Entity any = Boolean.False;
75+
for (var i = 0; i < statements.Count; i++)
76+
{
77+
var alone = statements[i];
78+
for (var j = 0; j < statements.Count; j++)
79+
if (j != i)
80+
alone &= !statements[j];
81+
any |= alone;
82+
}
83+
return any;
84+
}
85+
3286
private static Entity? Statement(Entity element, Entity set) => set switch
3387
{
3488
Unionf(var left, var right) => Statement(element, left) is { } inLeft && Statement(element, right) is { } inRight ? inLeft | inRight : null,
Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
//
2+
// Copyright (c) 2019-2026 Angouri.
3+
// AngouriMath is licensed under MIT.
4+
// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.
5+
// Website: https://am.angouri.org.
6+
//
7+
8+
using System.Numerics;
9+
using AngouriMath;
10+
using AngouriMath.Core.Exceptions;
11+
using AngouriMath.Extensions;
12+
using Xunit;
13+
14+
namespace AngouriMath.Tests.Common
15+
{
16+
/// <summary>
17+
/// A quantifier, a subset and a cardinality over a finite set compile, in FastExpression and in the LINQ compiler, to
18+
/// what evaluation gives: a quantifier as the connective of its body at each member, a subset as the memberships of
19+
/// its members, and a cardinality as the number of distinct values among them. Each was refused, and over any other
20+
/// set still is.
21+
/// <a href="https://github.com/asc-community/AngouriMath/issues/2195">#2195</a>
22+
/// </summary>
23+
[Trait("Area", "Common")]
24+
public sealed class FiniteSetStatementCompilationTest
25+
{
26+
// Not at NaN: see AtNaNTheValueIsUndecidedOrTheVacuousTruth.
27+
private static readonly string[] points = { "-1", "0", "1/2", "1", "2", "5/2", "3", "4", "i", "1 + i", "+oo", "-oo" };
28+
29+
private static Complex Numeric(string value) => ((Entity.Number.Complex)value.ToEntity().Evaled).ToNumerics();
30+
31+
private static Entity At(string expression, string point) => expression.ToEntity().Substitute("x", point);
32+
33+
private static bool Same(Complex expected, Complex actual)
34+
=> double.IsNaN(expected.Real) || double.IsNaN(expected.Imaginary)
35+
? double.IsNaN(actual.Real) || double.IsNaN(actual.Imaginary)
36+
: expected == actual;
37+
38+
[Theory]
39+
[InlineData("forall t in { 1, 2, 3 } : t < x")]
40+
[InlineData("exists t in { 1, 2, 3 } : t = x")]
41+
[InlineData("exists! t in { 1, 2, 3 } : t > x")]
42+
[InlineData("forall t in { 1, 2 } : exists s in { 2, 3 } : s > t + x")]
43+
[InlineData("forall t in { } : t = x")]
44+
[InlineData("exists t in { } : t = x")]
45+
[InlineData("{ x } subset [0; 3]")]
46+
[InlineData("{ x, 2 } subset ZZ")]
47+
[InlineData("{ } subset { x }")]
48+
public void AStatementOverAFiniteSetIsWhatEvaluationSays(string statement)
49+
{
50+
var fast = statement.ToEntity().Compile("x");
51+
var linq = statement.ToEntity().Compile<Complex, bool?>("x");
52+
var compared = 0;
53+
foreach (var a in points)
54+
{
55+
var evaluated = At(statement, a).Evaled;
56+
if (evaluated is not Entity.Boolean && !evaluated.IsNaN)
57+
continue;
58+
bool? expected = evaluated is Entity.Boolean truth ? (bool)truth : null;
59+
var x = Numeric(a);
60+
var value = fast.Call(x);
61+
bool? fastTruth = value == 1 ? true : value == 0 ? false : null;
62+
Assert.True(expected == fastTruth, $"{statement} at {a}: {expected?.ToString() ?? "none"} evaluated, {value} by FastExpression");
63+
Assert.True(expected == linq(x), $"{statement} at {a}: {expected?.ToString() ?? "none"} evaluated, {linq(x)?.ToString() ?? "none"} by LINQ");
64+
compared++;
65+
}
66+
Assert.True(compared >= points.Length / 2, $"only {compared} of {statement} decided");
67+
}
68+
69+
[Theory]
70+
[InlineData("card({ 1, x })")]
71+
[InlineData("card({ 1, 2, x, x^2 })")]
72+
[InlineData("card({ })")]
73+
public void ACardinalityIsWhatEvaluationSays(string expression)
74+
{
75+
var fast = expression.ToEntity().Compile("x");
76+
var linq = expression.ToEntity().Compile<Complex, Complex>("x");
77+
var compared = 0;
78+
foreach (var a in points)
79+
{
80+
if (At(expression, a).Evaled is not Entity.Number.Complex evaluated)
81+
continue;
82+
var expected = evaluated.ToNumerics();
83+
var x = Numeric(a);
84+
Assert.True(Same(expected, fast.Call(x)), $"{expression} at {a}: {expected} evaluated, {fast.Call(x)} by FastExpression");
85+
Assert.True(Same(expected, linq(x)), $"{expression} at {a}: {expected} evaluated, {linq(x)} by LINQ");
86+
compared++;
87+
}
88+
Assert.True(compared >= points.Length / 2, $"only {compared} of {expression} evaluated");
89+
}
90+
91+
/// <summary>
92+
/// At NaN the compiled value is undecided, or the vacuous truth of a quantifier over the empty set, where
93+
/// evaluation differs: a finite set drops a member whose value is NaN, so <c>{ NaN }</c> is <c>{ }</c> and
94+
/// <c>card({ 1, NaN })</c> is 1, and a NaN anywhere in a quantifier's body makes the quantifier NaN.
95+
/// </summary>
96+
[Theory]
97+
[InlineData("{ x } subset [0; 3]", double.NaN)]
98+
[InlineData("card({ 1, x })", double.NaN)]
99+
[InlineData("forall t in { } : t = x", 1)]
100+
[InlineData("exists t in { } : t = x", 0)]
101+
public void AtNaNTheValueIsUndecidedOrTheVacuousTruth(string expression, double expected)
102+
{
103+
var value = expression.ToEntity().Compile("x").Call(double.NaN);
104+
Assert.True(double.IsNaN(expected) ? double.IsNaN(value.Real) : value == expected, $"{expression} at NaN: {value}");
105+
}
106+
107+
[Theory]
108+
[InlineData("forall t in [0; 1] : t < x")]
109+
[InlineData("exists t in ZZ : t = x")]
110+
[InlineData("{ x } subset QQ")]
111+
[InlineData("card([0; x])")]
112+
public void OverAnyOtherSetItIsRefused(string expression)
113+
=> Assert.Throws<UncompilableNodeException>(() => expression.ToEntity().Compile("x"));
114+
}
115+
}

0 commit comments

Comments
 (0)