Repository navigation
Expand file tree
/
Copy pathQuantifierFacts.cs
More file actions
432 lines (410 loc) · 22.2 KB
/
Copy pathQuantifierFacts.cs
File metadata and controls
432 lines (410 loc) · 22.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
//
// Copyright (c) 2019-2026 Angouri.
// AngouriMath is licensed under MIT.
// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.
// Website: https://am.angouri.org.
//
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using AngouriMath.Core;
using PeterO.Numbers;
using static AngouriMath.Entity;
using static AngouriMath.Entity.Number;
using static AngouriMath.Entity.Set;
namespace AngouriMath.Functions.Boolean
{
/// <summary>
/// What the quantifiers around a statement establish while they decide it: each bound name
/// is a member of the set it ranges over, and a claim made under a hypothesis is made where
/// the hypothesis holds. A rule that needs one of those facts, such as that <c>p</c> is prime
/// or that <c>0 < k < p</c>, asks here.
/// </summary>
/// <remarks>
/// <para>
/// A node has no parent, so a rule inside a body cannot walk up to the quantifier that binds
/// its names. The quantifier hands the facts down instead, for as long as it takes to decide:
/// the set its name ranges over, and for <c>forall x in S : H implies C</c> the conjuncts of
/// <c>H</c> while <c>C</c> is simplified. They are never in scope while <c>H</c> itself is
/// simplified, or <c>H implies C</c> would lose its hypothesis. For <c>exists</c> and
/// <c>exists!</c> each conjunct of the body is simplified with the ones before it in scope.
/// Scopes nest, so the inner quantifier of <c>forall p in PP : forall k in ZZ : ...</c> knows
/// that <c>p</c> is prime. Nothing leaves a scope: a verdict reached with the facts is the
/// verdict on the quantified statement, which states them, and it carries no condition.
/// </para>
/// <para>
/// The bound name is renamed first, to a name no other expression has, and every fact is
/// about a renamed name. That is what keeps a verdict from escaping through a cache. A node
/// that caches its simplification can only have read a fact if it mentions a renamed name,
/// and every such node is built during this decision and is reachable from nothing else. A
/// cache keyed on the structure of an expression cannot serve it elsewhere either, since no
/// other expression has the name. For the same reason a conjunct of the hypothesis about the
/// free names alone is not recorded: a rule reading it could simplify a node that is shared.
/// A substitution stops at a binder, so an inner quantifier that binds the same name again
/// is not renamed through, and the outer facts about the name do not reach it.
/// </para>
/// <para>
/// Only a body in which a rule reads the facts is renamed and decided this way. Every other
/// statement is decided as it was, under its own names.
/// </para>
/// https://github.com/asc-community/AngouriMath/issues/1409
/// </remarks>
internal static class QuantifierFacts
{
/// <summary>One scope: the name it renamed, where it bound one, and what it establishes.</summary>
private sealed class Frame
{
internal readonly Variable? Renamed;
internal readonly Entity[] Facts;
internal readonly Frame? Next;
internal Frame(Variable? renamed, Entity[] facts, Frame? next) => (Renamed, Facts, Next) = (renamed, facts, next);
}
[System.ThreadStatic] private static Frame? top;
/// <summary>Numbers the renamed names, which is what makes each one unlike any other.</summary>
[ConcurrentField] private static long lastRenamed;
/// <summary>
/// Decides the quantified statement with the facts in scope, or <see langword="null"/>
/// where no rule in the body reads them, for the statement to be decided as before. The
/// verdict is <see langword="null"/> where it is not settled, beside the body simplified
/// as far as it went, under the name it was given.
/// </summary>
internal static (Entity? Verdict, Entity Body)? Decide(Quantifiers.Kind kind, Entity var, Entity over, Entity body, bool isExact)
{
if (var is not Variable x || over is not Set set || !body.Nodes.Any(Reads))
return null;
var renamed = Variable.CreateVariableUnchecked($"{x.Name}'{Interlocked.Increment(ref lastRenamed)}");
var mark = ProofRecording.Mark();
var enclosing = top;
top = new Frame(renamed, new[] { renamed.In(set) }, enclosing);
try
{
// One level down, so that what a rule records while the body is simplified is
// written under the statement the quantifier records when it decides.
var written = body.Substitute(x, renamed);
Entity simplified;
ProofRecording.Enter();
try
{
simplified = Simplified(kind, written, isExact);
}
finally
{
ProofRecording.Leave();
}
var verdict = Quantifiers.Decide(kind, renamed, set, simplified, isExact);
if (verdict is null)
ProofRecording.Rollback(mark);
// A body the facts made True is recorded as it was written: the decision's own
// step would otherwise read `forall k in ZZ : True`.
else if (kind == Quantifiers.Kind.All && simplified == Entity.Boolean.True)
ProofRecording.Restate(mark, new Forallf(renamed, set, written),
written is Impliesf(var hypothesis, var claim)
? $"{claim} holds for every {renamed} in {set} with {hypothesis}"
: $"the body holds for every {renamed} in {set}",
"intro");
ProofRecording.Rename(mark, renamed, x);
return (verdict is null ? null : Renamed(verdict, renamed, x), Renamed(simplified, renamed, x));
}
finally
{
top = enclosing;
}
}
/// <summary>
/// The body simplified with the facts in scope: a claim made under a hypothesis with the
/// conjuncts of the hypothesis in scope as well, and the hypothesis itself with only the
/// facts from outside it.
/// </summary>
private static Entity Simplified(Quantifiers.Kind kind, Entity body, bool isExact)
{
switch (kind, body)
{
// forall x in S : H implies C, and H1 implies (H2 implies C) with both in scope for C.
case (Quantifiers.Kind.All, Impliesf(var hypothesis, var claim)):
{
var assumed = hypothesis.InnerSimplified(isExact);
var enclosing = Establish(assumed);
Entity concluded;
try
{
concluded = Simplified(kind, claim, isExact);
}
finally
{
top = enclosing;
}
return new Impliesf(assumed, concluded).InnerSimplified(isExact);
}
// exists x in S : A and B and C, each conjunct with the ones before it in scope.
case (not Quantifiers.Kind.All, Andf):
{
var conjuncts = new List<Entity>();
var enclosing = top;
try
{
foreach (var conjunct in Andf.LinearChildren(body))
{
var simplified = conjunct.InnerSimplified(isExact);
conjuncts.Add(simplified);
Establish(simplified);
}
}
finally
{
top = enclosing;
}
return conjuncts.Aggregate((left, right) => new Andf(left, right)).InnerSimplified(isExact);
}
default:
return body.InnerSimplified(isExact);
}
}
/// <summary>
/// Puts in scope the conjuncts of <paramref name="statement"/> that mention a renamed
/// name, and returns what was in scope before.
/// </summary>
private static Frame? Establish(Entity statement)
{
var enclosing = top;
var facts = Andf.LinearChildren(statement).Where(MentionsARenamedName).ToArray();
if (facts.Length > 0)
top = new Frame(null, facts, enclosing);
return enclosing;
}
/// <summary>
/// The expression with <paramref name="from"/> read as <paramref name="to"/> everywhere,
/// the name a quantifier binds included, which a substitution leaves alone.
/// </summary>
internal static Entity Renamed(Entity expression, Variable from, Variable to)
=> expression.Replace(node => node switch
{
Variable name when name == from => to,
Quantifier quantifier when quantifier.Var == from => quantifier.New(to, quantifier.Over, quantifier.Body),
_ => node
});
/// <summary>
/// Whether a rule reads the facts at <paramref name="node"/>, which is what a body is
/// renamed and decided with the facts in scope for: a divisibility, a congruence or an
/// equation of residues by a modulus that is not a number, which the rules modulo a
/// prime read.
/// </summary>
private static bool Reads(Entity node) => node switch
{
// A membership in a set of whole numbers, which MembershipAsComparison reads, and a
// quantifier over one, whose listed witnesses are asked about such memberships.
Inf(not Number, SpecialSet whole) => Quantifiers.IsIntegerSet(whole),
Quantifier(_, SpecialSet over, _) => Quantifiers.IsIntegerSet(over),
Dividesf(not Number, _) or Congruentf(_, _, not Number) => true,
Equalsf(Modf(_, var modulus), Modf(_, var other)) => modulus is not Number && modulus == other,
_ => false
};
private static bool MentionsARenamedName(Entity expression)
{
if (top is null)
return false;
foreach (var name in expression.Vars)
for (var frame = top; frame is not null; frame = frame.Next)
if (frame.Renamed is { } renamed && renamed == name)
return true;
return false;
}
private static IEnumerable<Entity> InScope()
{
for (var frame = top; frame is not null; frame = frame.Next)
foreach (var fact in frame.Facts)
yield return fact;
}
/// <summary>
/// Whether <c>p divides binomial(p, k)</c> follows from the facts in scope: <c>p</c> is
/// prime and <c>k</c> is a whole number with <c>0 < k < p</c>. Then <c>p</c> divides
/// <c>p! = binomial(p, k) k! (p - k)!</c> and none of the factors of <c>k! (p - k)!</c>,
/// each of which is below the prime <c>p</c>. Sullivan and Mackey's Prob 8.9.24.
/// </summary>
internal static bool PrimeDividesItsBinomial(Entity p, Entity k)
{
if (top is null || !IsPrime(p) || !IsWhole(k) || !IsPositive(k) || !IsPositive(p - k))
return false;
if (ProofRecording.Recording)
ProofRecording.AddBelow(new Dividesf(p, new Binomialf(p, k)),
$"{p} is prime and 0 < {k} < {p}, so {p} divides {p}! = binomial({p}, {k}) {k}! ({p} - {k})! and none of the factors of {k}! ({p} - {k})!",
"Nat.Prime.dvd_choose_self", Entity.Boolean.True);
return true;
}
/// <summary>
/// <c>s in S</c> for a set of whole numbers, as the comparison it is where the facts in scope
/// make <c>s</c> a whole number: <c>s >= 0</c> in <c>ZZ*</c>, <c>s >= 1</c> in <c>ZZ+</c>, and
/// <c>True</c> in <c>ZZ</c>. <see langword="null"/> otherwise. Sullivan and Mackey's Prob
/// 4.11.6 asks for a <c>z</c> in <c>ZZ*</c> with <c>x - y = z</c> or <c>y - x = z</c>, for whole
/// <c>x</c> and <c>y</c>: the witnesses are <c>x - y</c> and <c>y - x</c>, one of which is
/// not negative.
/// </summary>
internal static Entity? MembershipAsComparison(Entity element, Set set)
{
if (top is null || element is Number || !MentionsARenamedName(element) || !IsWholePolynomial(element))
return null;
return set switch
{
SpecialSet.Integers => Entity.Boolean.True,
SpecialSet.NonNegativeIntegers => element >= Integer.Zero,
SpecialSet.PositiveIntegers => element >= Integer.One,
_ => null,
};
}
/// <summary>
/// Whether <c>p divides d</c> by the binomial theorem, with the facts in scope: <c>p</c> is
/// prime, <c>d</c> is a polynomial with whole coefficients in whole quantities, and
/// writing each power <c>(u + v)^p</c> in it as <c>u^p + v^p</c> leaves nothing, or only
/// multiples of <c>p</c>. What the binomial theorem adds to <c>u^p + v^p</c> is
/// <c>binomial(p, k) u^k v^(p - k)</c> for <c>0 < k < p</c>, each a multiple of
/// <c>p</c> by <see cref="PrimeDividesItsBinomial"/>. That is asked of the quantifiers
/// first, and recorded as the step this one rests on. A difference is read the same way,
/// since <c>(-v)^p</c> is <c>-v^p</c> modulo every prime, 2 included. Sullivan and
/// Mackey's Prob 8.9.25, the freshman's dream.
/// </summary>
internal static bool PrimeDividesByTheBinomialTheorem(Entity p, Entity d)
{
if (top is null || !IsPrime(p) || !d.Nodes.Any(node => node is Powf(Sumf or Minusf, var exponent) && exponent == p))
return false;
var dreamt = d.Replace(node => node is Powf(Sumf or Minusf, var exponent) && exponent == p ? PowersOfTheTerms(((Powf)node).Base, p) : node);
// Read as polynomials over the same atoms, each of which must be the p-th power of a
// whole quantity for a congruence modulo p to carry through a product with it.
var atoms = new Dictionary<Entity, Variable>();
var unfolded = new Dictionary<Entity, Entity>();
var before = Quantifiers.Atomized(d, atoms, unfolded);
var after = Quantifiers.Atomized(dreamt, atoms, unfolded);
foreach (var atom in atoms.Keys)
if (atom is not Powf(var @base, var exponent) || exponent != p || !IsWholePolynomial(@base))
return false;
var names = before.Vars.Concat(after.Vars).Distinct().ToArray();
if (names.Length > MultivariatePolynomial.MaxVariables || names.Any(name => !atoms.ContainsValue(name) && !IsWhole(name)))
return false;
var indices = new Dictionary<Variable, int>();
for (var i = 0; i < names.Length; i++)
indices[names[i]] = i;
if (MultivariatePolynomial.TryParse(before, indices) is not { HasIntegerCoefficients: true }
|| MultivariatePolynomial.TryParse(after, indices) is not { } left
|| !(left.IsZero || p is Variable modulus && indices.TryGetValue(modulus, out var at) && left.HasIntegerCoefficients && left.Terms.All(term => MultivariatePolynomial.PowerOf(term.Key, at) > 0)))
return false;
// The step this rests on, p divides binomial(p, k) for 0 < k < p, asked of the
// quantifiers with the facts that p is prime already in scope.
var k = (d + p).Vars.Any(name => name.Name == "k") ? Variable.CreateUnique(d + p, "k") : MathS.Var("k");
ProofRecording.Enter();
Entity binomials;
try
{
binomials = new Forallf(k, MathS.Sets.Z, (Integer.Zero < k & k < p).Implies(new Dividesf(p, new Binomialf(p, k)))).InnerSimplified;
}
finally
{
ProofRecording.Leave();
}
if (binomials != Entity.Boolean.True)
return false;
if (ProofRecording.Recording)
ProofRecording.AddBelow(new Dividesf(p, d),
$"by the binomial theorem each ({string.Join("), (", d.Nodes.OfType<Powf>().Where(power => power.Base is Sumf or Minusf && power.Exponent == p).Select(power => power.Base).Distinct())})^{p} is the sum of the {p}-th powers of its terms and multiples of {p}, and what is left of {d} is a multiple of {p}",
"add_pow_char", Entity.Boolean.True);
return true;
}
/// <summary>The p-th powers of the terms of a sum, added: <c>(u - v)^p</c> is read as <c>u^p - v^p</c>.</summary>
private static Entity PowersOfTheTerms(Entity sum, Entity p)
=> Sumf.LinearChildren(sum)
.Select(term => term switch
{
Mulf(Integer { EInteger: var minusOne }, var rest) when minusOne.Equals(EInteger.FromInt32(-1)) => -rest.Pow(p).InnerSimplified,
Integer { IsNegative: true } negative => -((Entity)(-negative)).Pow(p).InnerSimplified,
_ => term.Pow(p).InnerSimplified
})
.Aggregate((left, right) => left + right);
/// <summary>Whether the expression is a polynomial with whole coefficients in names that are whole by the facts in scope.</summary>
private static bool IsWholePolynomial(Entity expression)
{
var names = expression.Vars.Distinct().ToArray();
if (names.Length > MultivariatePolynomial.MaxVariables || names.Any(name => !IsWhole(name)))
return false;
var indices = new Dictionary<Variable, int>();
for (var i = 0; i < names.Length; i++)
indices[names[i]] = i;
return MultivariatePolynomial.TryParse(expression, indices) is { HasIntegerCoefficients: true };
}
private static bool IsPrime(Entity expression)
=> expression is Integer number ? Functions.Primes.IsPrime(number.EInteger) == true : IsIn(expression, 0);
private static bool IsWhole(Entity expression)
=> expression is Integer || IsIn(expression, 3);
/// <summary>
/// Whether the facts in scope put <paramref name="element"/> in the set of numbers ranked
/// <paramref name="rank"/> by <see cref="Rank"/>, or in one inside it.
/// </summary>
private static bool IsIn(Entity element, int rank)
{
if (!MentionsARenamedName(element))
return false;
foreach (var fact in InScope())
if (fact is Inf(var member, SpecialSet within) && member == element && Rank(within) is var inner and >= 0 && inner <= rank)
return true;
return false;
}
/// <summary>The sets of numbers, each inside the next: PP, ZZ+, ZZ*, ZZ, QQ, RR, CC.</summary>
private static int Rank(SpecialSet set) => set switch
{
SpecialSet.Primes => 0,
SpecialSet.PositiveIntegers => 1,
SpecialSet.NonNegativeIntegers => 2,
SpecialSet.Integers => 3,
SpecialSet.Rationals => 4,
SpecialSet.Reals => 5,
SpecialSet.Complexes => 6,
_ => -1
};
/// <summary>
/// Whether <paramref name="expression"/> is positive by the facts in scope. Each fact bounds
/// a quantity below: <c>a > b</c> and <c>b < a</c> say <c>a - b > 0</c>, and a
/// member of the primes, the positive or the non-negative whole numbers is at least 2, 1
/// or 0. The expression is positive where it is such a quantity plus a constant that is
/// not negative, or plus a positive one where the bound is not strict: <c>p - 1</c> for a
/// prime <c>p</c> is <c>p - 2</c> plus 1.
/// </summary>
private static bool IsPositive(Entity expression)
{
if (expression is Real number)
return number.IsPositive;
if (!MentionsARenamedName(expression))
return false;
foreach (var fact in InScope())
{
var bound = fact switch
{
Lessf(var smaller, var greater) => (Difference: greater - smaller, Strict: true),
Greaterf(var greater, var smaller) => (greater - smaller, true),
LessOrEqualf(var smaller, var greater) => (greater - smaller, false),
GreaterOrEqualf(var greater, var smaller) => (greater - smaller, false),
Inf(var member, SpecialSet.Primes) => (member - 2, false),
Inf(var member, SpecialSet.PositiveIntegers) => (member - 1, false),
Inf(var member, SpecialSet.NonNegativeIntegers) => (member, false),
_ => ((Entity Difference, bool Strict)?)null
};
if (bound is var (difference, strict) && Gap(expression, difference) is { } gap
&& (strict ? gap.Sign >= 0 : gap.Sign > 0))
return true;
}
return false;
}
/// <summary>
/// The constant <c>a - b</c>, where the two differ by one as polynomials, and
/// <see langword="null"/> otherwise.
/// </summary>
private static ERational? Gap(Entity a, Entity b)
{
var difference = a - b;
var names = difference.Vars.Distinct().ToArray();
if (names.Length > MultivariatePolynomial.MaxVariables)
return null;
var indices = new Dictionary<Variable, int>();
for (var i = 0; i < names.Length; i++)
indices[names[i]] = i;
if (MultivariatePolynomial.TryParse(difference, indices) is not { IsConstant: true } constant)
return null;
return constant.IsZero ? ERational.Zero : constant.Terms.Single().Value;
}
}
}