Repository navigation
Expand file tree
/
Copy pathQuantifiers.cs
More file actions
1702 lines (1636 loc) · 94 KB
/
Copy pathQuantifiers.cs
File metadata and controls
1702 lines (1636 loc) · 94 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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// 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 AngouriMath.Core;
using AngouriMath.Core.Exceptions;
using PeterO.Numbers;
using static AngouriMath.Entity;
using static AngouriMath.Entity.Number;
using static AngouriMath.Entity.Set;
namespace AngouriMath.Functions.Boolean
{
/// <summary>
/// Decides <c>forall x in S : P</c>, <c>exists x in S : P</c> and <c>exists! x in S : P</c>
/// where a decision is available, and says nothing where it is not.
/// </summary>
/// <remarks>
/// <para>
/// Three routes, in the order Sullivan and Mackey's proofs book (#1409) teaches them. Over a <b>finite set</b> the body
/// is evaluated at every member, which is the definition; a member the body cannot decide
/// leaves the statement as written unless the members it can decide settle it, as one
/// counterexample settles <c>forall</c>. Over an infinite set the first thing tried is a
/// <b>named witness</b>: a handful of members of the set, chosen for being where a claim
/// usually fails — 0, ±1, ±2, a half, an end of an interval, <c>i</c> in the complex numbers
/// — and a member where the body is false disproves <c>forall</c> exactly as one where it
/// is true proves <c>exists</c>. What a witness cannot do is prove <c>forall</c> or refute
/// <c>exists</c>, and for that the <b>solver</b> is asked: <c>exists x in S : P</c> holds
/// where the solution set of <c>P</c> meets <c>S</c>, and <c>forall x in S : P</c> where the
/// solution set of <c>not P</c> does not.
/// </para>
/// <para>
/// The solver route is taken only where what it answers is what was asked. Its answer to an
/// order comparison is a set of reals, so it is asked one only over a set of reals; its
/// default for a statement it has no arm for is the empty set, which as an answer to
/// "where does this hold" is a claim, so it is asked only about the shapes it has arms for
/// — comparisons of two expressions that mention the variable, joined by the connectives.
/// Whether the solution set meets <c>S</c> is read off the two sets by
/// <see cref="Meets"/>, and where that cannot be read — a set-builder the solver fell back to,
/// a member whose membership is undecided — the answer is that there is none.
/// </para>
/// <para>
/// Uniqueness is existence with a count: over a finite set of numbers, whose members are
/// distinct exactly when unequal; over anything else, from the solver's solution set when it
/// is a finite set of numbers. A set with a symbol in it is not counted, since two of its
/// members may be one.
/// </para>
/// https://github.com/asc-community/AngouriMath/issues/1409
/// </remarks>
internal static class Quantifiers
{
internal enum Kind { All, Some, Unique }
/// <summary>Set while two nested quantifiers are decided in the other order, so that they are not swapped back.</summary>
[System.ThreadStatic] private static bool swapping;
/// <summary>
/// The truth value of the quantified statement, or <see langword="null"/> where it is
/// not settled. The set and the body arrive already simplified.
/// </summary>
internal static Entity? Decide(Kind kind, Entity var, Entity over, Entity body, bool isExact)
{
// One read per decision, and nothing recorded or allocated unless a scope is open.
if (!ProofRecording.Recording)
return DecideBy(kind, var, over, body, isExact, out _);
ProofRecording.Enter();
var mark = ProofRecording.Mark();
try
{
var verdict = DecideBy(kind, var, over, body, isExact, out var by);
// A decision that came to nothing leaves nothing behind: what was tried on
// the way is not part of any proof.
if (verdict is null)
ProofRecording.Rollback(mark);
else if (by is var (rule, lemma))
ProofRecording.Add(Quantified(kind, var, over, body), rule, lemma, verdict);
return verdict;
}
finally
{
ProofRecording.Leave();
}
}
private static Entity Quantified(Kind kind, Entity var, Entity over, Entity body)
=> kind switch
{
Kind.All => new Forallf(var, over, body),
Kind.Some => new Existsf(var, over, body),
_ => new ExistsUniquef(var, over, body),
};
/// <summary>
/// <see cref="Decide"/> proper, naming the rule that decided in <paramref name="by"/> --
/// as the reference names it, and as the Lean 4 tactic or lemma a checker would use --
/// and <see langword="null"/> for a route that only asked another statement.
/// </summary>
private static Entity? DecideBy(Kind kind, Entity var, Entity over, Entity body, bool isExact, out (string Rule, string Lemma)? by)
{
by = null;
if (var is not Variable x || over is not Set set)
return null;
// A statement about the members of { y in S : Q } is a statement about the members of
// S that satisfy Q, and that shape is what the routes below read.
if (set is ConditionalSet builder)
{
if (builder.DeclaredMembership is not (var declared, var rest) || builder.Var is not Variable y)
return null;
var condition = rest.Substitute(y, x);
by = ("the members of { y in S : Q } are the members of S with Q", "Set.mem_setOf_eq");
return Decide(kind, x, declared.InnerSimplified(isExact), kind switch
{
Kind.All => condition.Implies(body),
_ => condition & body,
}, isExact);
}
if (set is SpecialSet.Booleans)
set = new FiniteSet(Entity.Boolean.True, Entity.Boolean.False);
if (!body.ContainsNode(x))
{
by = ("the body does not mention the name, so it says the same of every member", "forall_const");
return Closed(kind, set, body);
}
// A statement about the members that satisfy a condition on the name alone is the
// statement over the set cut down to them: forall k in ZZ : (0 < k and k < 7) implies
// 7 divides binomial(7, k) -- Sullivan and Mackey's Prob 8.9.24 at p = 7 -- is the
// statement over {1, ..., 6}. The converse of the set-builder route above, so the cut
// is taken only where it comes out listed, or as the whole numbers from a least one,
// which the routes below read -- never as a set-builder again.
// https://github.com/asc-community/AngouriMath/issues/1409
if (set is SpecialSet whole && IsIntegerSet(whole) && CutByHypothesis(kind, x, whole, body, isExact) is var (cutSet, cutCondition, cutRest))
{
by = ($"the members that satisfy {cutCondition} are {cutSet}", "Set.mem_setOf_eq");
return Decide(kind, x, cutSet, cutRest, isExact);
}
// The whole numbers from m are ZZ* shifted by m, so a statement over ZZ+ /\ [4; +oo)
// is the statement about 4 + t over ZZ*, where every route below reads the set.
if (set is Intersectionf cut && LeastMember(cut) is { } start && IsUnboundedAbove(cut))
{
var t = Variable.CreateUnique(body + start, "t");
by = ($"the whole numbers from {start} are ZZ* shifted by {start}", "Nat.le_induction");
return Decide(kind, t, MathS.Sets.NonNegativeIntegers, body.Substitute(x, start + t).InnerSimplified(isExact), isExact);
}
// forall x in S : forall y in T : B is forall y in T : forall x in S : B where neither
// set mentions the other name, and so for exists. A closed form's range condition is
// about the name it runs to, and when that name is bound outside, the condition
// reaches the quantifier inside as a piecewise it cannot decide:
// forall n in ZZ* : forall r in ZZ* : sum(binomial(r + i, i), i, 0, n) = ... leaves
// `n >= 0` to the quantifier over r. With the two swapped, the quantifier over n
// decides it. Tried only where the inner body is such a piecewise, and once.
// https://github.com/asc-community/AngouriMath/issues/1409
if (!swapping && kind is Kind.All or Kind.Some && body is Forallf or Existsf && body is Quantifier(Variable other, Set innerSet, Piecewise inner)
&& (body is Forallf) == (kind == Kind.All) && other != x && !innerSet.ContainsNode(x) && !set.ContainsNode(other)
&& inner.Cases.Any(@case => @case.Predicate.ContainsNode(x) && !@case.Predicate.ContainsNode(other)))
{
swapping = true;
Entity? swapped;
try
{
swapped = Decide(kind, other, innerSet, Quantified(kind, x, set, inner).InnerSimplified(isExact), isExact);
}
finally
{
swapping = false;
}
if (swapped is Entity.Boolean)
{
by = ($"the two quantifiers of one kind are taken in the other order, so the condition on {x} is decided by the quantifier over it", kind == Kind.All ? "forall_swap" : "exists_swap");
return swapped;
}
}
// A piecewise body -- what a closed form comes as, sum(k, k, 1, n) being
// (n + n^2)/2 provided n >= 0 -- is the case whose condition holds at every member of
// the set, or the next case where a condition holds at none: over ZZ+ the condition
// n >= 0 is the membership itself, and the statement is about the closed form.
// https://github.com/asc-community/AngouriMath/issues/1409
if (body is Piecewise piecewise)
{
var cases = piecewise.Cases.ToList();
for (var i = 0; i < cases.Count; i++)
{
var @case = cases[i];
var holds = @case.Predicate == Entity.Boolean.True ? Entity.Boolean.True : Decide(Kind.All, x, set, @case.Predicate.InnerSimplified(isExact), isExact);
if (holds == Entity.Boolean.True)
{
by = ($"the case {@case.Predicate} of the piecewise body holds at every member, so the body is that case", "if_pos");
return Decide(kind, x, set, @case.Expression.InnerSimplified(isExact), isExact);
}
// A case whose condition is a statement about a parameter beside one that
// holds at every member -- `q = 1 and n >= 0`, which is how a sum with a
// symbolic ratio comes -- is the case under that hypothesis and the cases
// after it under its negation: the statement is decided in each, and holds
// provided the hypothesis where it holds there alone. Sullivan and Mackey's
// Ex 5.2.6, the geometric sum with `q = 1` set aside.
if (SplitOffParameterCondition(@case.Predicate, x, set, isExact) is (Entity hypothesis, var atOne))
{
var under = (atOne is var (parameter, value) ? @case.Expression.Substitute(parameter, value) : @case.Expression).InnerSimplified(isExact);
var probedUnder = ProofRecording.Mark();
var whenItHolds = Decide(kind, x, set, under, isExact);
if (whenItHolds != Entity.Boolean.True)
ProofRecording.Rollback(probedUnder);
var rest = i + 1 >= cases.Count ? null
: i + 2 == cases.Count && cases[i + 1].Predicate == Entity.Boolean.True ? cases[i + 1].Expression
: MathS.Piecewise(cases.Skip(i + 1));
var otherwise = rest is null ? null : Decide(kind, x, set, rest.InnerSimplified(isExact), isExact);
// Each verdict is True, True under a condition of its own, False, or
// nothing; the statement is True under the disjunction of the two cases
// where each holds, and False where both fail.
var (holdsUnder, conditionUnder) = TrueUnder(whenItHolds);
var (holdsOtherwise, conditionOtherwise) = TrueUnder(otherwise);
if (holdsUnder && holdsOtherwise)
{
by = ($"the statement holds both under {hypothesis} and under its negation", "by_cases");
return conditionUnder == Entity.Boolean.True && conditionOtherwise == Entity.Boolean.True ? Entity.Boolean.True
: Entity.Boolean.True.Provided((hypothesis & conditionUnder) | (!hypothesis & conditionOtherwise));
}
if (holdsOtherwise && whenItHolds is null or Entity.Boolean(false) or Number { IsNaN: true } or Providedf(Number { IsNaN: true }, _))
{
by = ($"the statement holds under the negation of {hypothesis}, and not as it stands under it", "by_cases");
return Entity.Boolean.True.Provided(conditionOtherwise == Entity.Boolean.True ? !hypothesis : WithoutRepeatedExclusions(!hypothesis & conditionOtherwise));
}
if (holdsUnder && otherwise is Entity.Boolean(false))
{
by = ($"the statement holds under {hypothesis} and fails under its negation", "by_cases");
return Entity.Boolean.True.Provided(conditionUnder == Entity.Boolean.True ? hypothesis : WithoutRepeatedExclusions(hypothesis & conditionUnder));
}
break;
}
var probed = ProofRecording.Mark();
var somewhere = Decide(Kind.Some, x, set, @case.Predicate.InnerSimplified(isExact), isExact);
ProofRecording.Rollback(probed);
if (somewhere != Entity.Boolean.False)
break;
}
}
// forall b in B : exists a in A : f(a) = b is the statement that B lies in the image
// of A under f -- surjectivity onto B (Sullivan and Mackey's Def 7.4.1) -- and the image is
// a set the library computes: listed over a listed A, an interval by interval
// arithmetic, so the subset decision settles it where the image evaluates.
// https://github.com/asc-community/AngouriMath/issues/1409
if (kind == Kind.All && body is Existsf(Variable a, Set domain, Equalsf(var lhs, var rhs))
&& (lhs == x && !rhs.ContainsNode(x) && rhs.ContainsNode(a) ? rhs : rhs == x && !lhs.ContainsNode(x) && lhs.ContainsNode(a) ? lhs : null) is { } map)
{
var image = new IndexedUnionf(a, domain, new FiniteSet(map)).InnerSimplified(isExact);
if (image is not IndexedUnionf && image is Set imageSet && Core.Sets.SetOperators.Subset(set, imageSet, isExact) is { } covered)
{
by = ($"every b has an a with f(a) = b exactly when the set lies in the image of f, which is {image}", "Set.range_subset_iff");
return covered;
}
}
// An equation whose two sides differ by a polynomial that expands to nothing holds
// at every member, whatever the set: (x + 1)^2 = x^2 + 2 x + 1 is True of each.
if (body is Equalsf(var left, var right))
{
var tried = ProofRecording.Mark();
if (IsIdentity(left, right, x, set, isExact) is { } identity)
{
by = ("the two sides differ by a polynomial that expands to nothing", "ring");
return Closed(kind, set, Entity.Boolean.True) is Entity.Boolean(true) ? identity : Closed(kind, set, Entity.Boolean.True);
}
ProofRecording.Rollback(tried);
}
if (set is FiniteSet finite)
{
by = ($"evaluated at each of the {finite.Count} members", "decide");
return OverFinite(kind, x, finite, body, isExact);
}
if (set is SpecialSet integers && IsIntegerSet(integers) && kind != Kind.Unique)
{
// A statement about divisibility, or a congruence, in a polynomial of x with
// whole coefficients repeats with the modulus, so the residues decide it:
// forall n in ZZ : 6 divides n^3 + 5 n is six cases. Sullivan and Mackey's "case
// analysis over the classes" (Ex 6.5.14).
if (Period(body, x, integers) is { } period && period.CompareTo(EInteger.FromInt32(LargestPeriod)) <= 0)
{
by = ($"the statement repeats modulo {period}, so its {period} residues decide it", "decide");
return OverResidues(kind, x, integers, body, period, isExact);
}
// A polynomial equation with no solution modulo some m has none in the whole
// numbers: 3 x^2 - 5 y^2 = 1 is impossible modulo 5 (Ex 6.5.27). Only a refusal
// is read off the residues; a solution modulo every m tried proves nothing.
if (ImpossibleByResidues(kind, x, integers, body) is { } verdict)
{
by = ("the equation has no solution modulo a small m, so none in the whole numbers", "decide");
return verdict;
}
}
// A statement about a sum or a product up to x, over the whole numbers from some
// least one, is proved by induction: it holds at the least member, and holding at
// x it holds at x + 1, where the sum to x + 1 is the sum to x and one more term.
// Sullivan and Mackey's chapter 5. https://github.com/asc-community/AngouriMath/issues/1409
if (kind == Kind.All && LeastMember(set) is { } least && ByInduction(x, set, least, body, isExact) is { } byInduction)
{
by = byInduction == Entity.Boolean.False
? ($"false at the least member, {least}", "decide")
: ($"by induction from {least}: the base case, and the sum to {x} + 1 unfolded by one term with the hypothesis for the sum to {x}", "Nat.le_induction");
return byInduction;
}
// And an inequality with an exponential or a factorial in x, by induction with the
// step read off a multiple of the hypothesis: P(x + 1) = c P(x) + D with c >= 0 and
// D >= 0 keeps P >= 0 (Sullivan and Mackey's Ex 5.3.2, Prob 5.7.2, 5.7.8).
if (kind == Kind.All && LeastMember(set) is { } first && ByInductionOnAnInequality(x, set, first, body, isExact) is { } byGrowth)
{
by = byGrowth == Entity.Boolean.False
? ($"false at the least member, {first}", "decide")
: ($"by induction from {first}: the base case, and P({x} + 1) = c P({x}) + D with c >= 0 and D >= 0", "Nat.le_induction");
return byGrowth;
}
// A congruence modulo a symbol, by the residue of the difference of its sides: the
// same at one member and at the next along a row of whole numbers, so the same at
// every member. Fermat's little theorem, Sullivan and Mackey's Prob 8.9.26.
// https://github.com/asc-community/AngouriMath/issues/1409
if (kind == Kind.All && set is SpecialSet row && IsIntegerSet(row) && ByTheResidueOfADifference(x, row, body, isExact, out var how) is { } byResidue)
{
by = how;
return byResidue;
}
if (Witness(kind, x, set, body, isExact) is { } byWitness)
{
by = (byWitness == Entity.Boolean.False && kind == Kind.All ? "a member at which the body is false"
: byWitness == Entity.Boolean.True && kind == Kind.Some ? "a member at which the body is true"
: "two members at which the body is true", "exact ⟨_, by decide⟩");
return byWitness;
}
if (BySolving(kind, x, set, body) is { } bySolving)
{
by = ((kind, bySolving == Entity.Boolean.True) switch
{
(Kind.All, true) => "the negation of the body has no solution in the set",
(Kind.All, false) => "the negation of the body has a solution in the set",
(Kind.Some, true) => "the body's solutions meet the set",
(Kind.Some, false) => "the body has no solution in the set",
(_, true) => "the body has exactly one solution in the set",
_ => "the body has no solution, or more than one, in the set",
}, "nlinarith");
return bySolving;
}
return null;
}
/// <summary>
/// The least member of a set of whole numbers bounded below -- <c>ZZ+</c>, <c>ZZ*</c>,
/// either cut by an interval -- or <see langword="null"/> where the set is something else.
/// </summary>
internal static Integer? LeastMember(Set set)
{
switch (set)
{
case SpecialSet special:
return special.ToDomain() switch
{
Domain.PositiveInteger => Integer.One,
Domain.NonNegativeInteger => Integer.Zero,
_ => null,
};
case Intersectionf(Set left, Set right):
{
var (integers, cut) = (left, right) switch
{
(SpecialSet whole, Interval interval) when IsIntegerSet(whole) => (whole, interval),
(Interval interval, SpecialSet whole) when IsIntegerSet(whole) => (whole, interval),
_ => (null, null),
};
if (integers is null || cut is null || cut.Left.Evaled is not Real { IsFinite: true } low)
return null;
var floor = low.EDecimal.RoundToExponent(0, ERounding.Floor).ToEInteger();
// The first whole number at or after the end: the end itself when it
// is whole and included, the next one otherwise.
var first = Integer.Create(low.EDecimal.IsInteger() && cut.LeftClosed ? floor : floor + 1);
var own = LeastMember(integers);
return own is not null && own > first ? own : first;
}
default:
return null;
}
}
/// <summary>
/// <c>forall x in S : sum(f, k, a, x) = g</c> by induction from the least member of
/// <c>S</c>: the statement at that member evaluates to <see langword="true"/>, and the
/// statement at <c>x + 1</c>, with the sum to <c>x + 1</c> unfolded to the sum to <c>x</c>
/// plus <c>f(x + 1)</c> and that sum then replaced by <c>g</c> -- the hypothesis -- holds
/// at every member. A product unfolds with a factor. Only the shape with one sum or
/// product, standing alone on a side of the equation, is read; a statement that fails at
/// the least member is <see langword="false"/>.
/// </summary>
private static Entity? ByInduction(Variable x, Set set, Integer least, Entity body, bool isExact)
{
if (body is not Equalsf(var left, var right))
return null;
var (accumulated, closed) = (left, right) switch
{
(Summationf or Productf, _) when !right.ContainsNode(left) => (left, right),
(_, Summationf or Productf) when !left.ContainsNode(right) => (right, left),
_ => (null, null),
};
if (accumulated is null || closed is null)
return null;
var (term, index, from, to) = accumulated switch
{
Summationf sum => (sum.Expression, sum.Var, sum.From, sum.To),
Productf product => (product.Expression, product.Var, product.From, product.To),
_ => throw new AngouriBugException("A sum or a product was matched above"),
};
// The upper bound is x, or x plus a whole number after a shift of the set.
if (WholeGap(to, x) is null || from.ContainsNode(x) || term.ContainsNode(x) || index is not Variable k)
return null;
var atLeast = body.Substitute(x, least).InnerSimplified(isExact);
var tried = ProofRecording.Mark();
if (atLeast is Equalsf(var l, var r) && IsIdentity(l, r, x, set, isExact) is { } identity)
atLeast = identity;
else
ProofRecording.Rollback(tried);
if (atLeast is Entity.Boolean or Providedf)
ProofRecording.AddBelow(body.Substitute(x, least), $"the base case, at {least}, by evaluation", "decide", atLeast);
if (atLeast == Entity.Boolean.False)
return Entity.Boolean.False;
if (Truth(atLeast) is not { } baseCondition)
return null;
var next = x + Integer.One;
var oneMore = term.Substitute(k, to.Substitute(x, next));
var unfolded = accumulated is Summationf ? closed + oneMore : closed * oneMore;
var step = new Equalsf(unfolded, closed.Substitute(x, next)).InnerSimplified(isExact);
if (Truth(Decide(Kind.All, x, set, step, isExact)) is not { } stepCondition)
return null;
return Entity.Boolean.True.Provided((baseCondition & stepCondition).InnerSimplified(isExact));
}
/// <summary>
/// <c>forall x in S : f = g (mod m)</c>, or <c>f mod m = g mod m</c>, over a row of whole
/// numbers, where <c>m</c> is not a number and does not mention <c>x</c>. With
/// <c>D = f - g</c>: where <c>m</c> divides <c>D</c> at every member the statement holds.
/// Otherwise, where it holds at one member and <c>m</c> divides <c>D(x + 1) - D(x)</c> at
/// every member, <c>D</c> has one residue modulo <c>m</c> the whole way along the row, up
/// from that member and down from it, so it holds at every member. Fermat's little
/// theorem is the second, with the difference <c>(a + 1)^p - a^p - 1</c> read by the
/// binomial theorem.
/// </summary>
private static Entity? ByTheResidueOfADifference(Variable x, SpecialSet set, Entity body, bool isExact, out (string Rule, string Lemma)? how)
{
how = null;
var (difference, modulus) = body switch
{
Congruentf(var left, var right, var m) => (left - right, m),
Equalsf(Modf(var left, var m), Modf(var right, var n)) when m == n => (left - right, m),
_ => ((Entity?)null, (Entity?)null)
};
if (difference is null || modulus is null or Number || modulus.ContainsNode(x))
return null;
var tried = ProofRecording.Mark();
if (Divides(modulus, difference, isExact, deeper: false))
{
how = ($"{modulus} divides {difference} at every member", "Int.modEq_iff_dvd");
return Entity.Boolean.True;
}
ProofRecording.Rollback(tried);
// A member at which the statement is decided: the least one, then 1, 0 and -1.
Integer? start = null;
foreach (var member in new[] { LeastMember(set), Integer.One, Integer.Zero, Integer.MinusOne }.OfType<Integer>().Distinct())
{
if (LeastMember(set) is { } least && member < least)
continue;
var at = body.Substitute(x, member).InnerSimplified(isExact);
if (at == Entity.Boolean.False)
{
ProofRecording.AddBelow(body.Substitute(x, member), $"false at {member}, by evaluation", "decide", at);
how = ($"false at {member}", "decide");
return at;
}
if (at == Entity.Boolean.True)
{
ProofRecording.AddBelow(body.Substitute(x, member), $"the base case, at {member}, by evaluation", "decide", at);
start = member;
break;
}
}
if (start is null)
return null;
var step = difference.Substitute(x, x + Integer.One) - difference;
if (!Divides(modulus, step, isExact, deeper: true))
{
ProofRecording.Rollback(tried);
return null;
}
ProofRecording.AddBelow(new Forallf(x, set, new Dividesf(modulus, step)), $"{modulus} divides the difference at {x} + 1 less the difference at {x}, at every member", "intro", Entity.Boolean.True);
how = ($"by induction up and down from {start}: {modulus} divides the difference of the two sides there, and the difference changes by a multiple of {modulus} from each member to the next", "Int.inductionOn'");
return Entity.Boolean.True;
}
/// <summary>
/// Whether <c>m divides d</c> simplifies to true, with what it rests on recorded under
/// the decision, or <paramref name="deeper"/> under a step the caller records itself.
/// </summary>
private static bool Divides(Entity modulus, Entity difference, bool isExact, bool deeper)
{
if (deeper)
ProofRecording.Enter();
try
{
return new Dividesf(modulus, difference).InnerSimplified(isExact) == Entity.Boolean.True;
}
finally
{
if (deeper)
ProofRecording.Leave();
}
}
private static bool IsUnboundedAbove(Intersectionf cut)
=> (cut.Left as Interval ?? cut.Right as Interval) is { } interval && interval.Right.Evaled is Real { EDecimal: var end } && end.IsInfinity() && !end.IsNegative;
/// <summary>
/// <c>forall x in S : L > R</c> (or <c>>=</c>, <c><</c>, <c><=</c>) with an exponential
/// or a factorial in <c>x</c>, from the least member of <c>S</c>: it holds there, and
/// with <c>P = L - R</c>, <c>P(x + 1) = c P(x) + D</c> for a multiplier <c>c >= 0</c> --
/// <c>1</c>, the base of an exponential, <c>x + 1</c> beside a factorial -- and a
/// remainder <c>D >= 0</c> read by the sign calculus, so that <c>P(x) >= 0</c> carries to
/// <c>x + 1</c>; strictly, where <c>c > 0</c> or <c>D > 0</c>.
/// </summary>
private static Entity? ByInductionOnAnInequality(Variable x, Set set, Integer least, Entity body, bool isExact)
{
var (positive, strict) = body switch
{
Greaterf(var l, var r) => (l - r, true),
GreaterOrEqualf(var l, var r) => (l - r, false),
Lessf(var l, var r) => (r - l, true),
LessOrEqualf(var l, var r) => (r - l, false),
_ => (null, false),
};
if (positive is null || !positive.Nodes.Any(node => node is Powf(_, var e) && e.ContainsNode(x) || node is Factorialf f && f.ContainsNode(x)))
return null;
// The sign calculus asks the decision about polynomials only, so the step never asks
// for an inequality of this shape again; the guard is against that ceasing to hold.
if (inductionDepth > 0)
return null;
inductionDepth++;
try
{
return ByInductionOnAnInequalityCore(x, set, least, body, positive, strict, isExact);
}
finally
{
inductionDepth--;
}
}
[System.ThreadStatic] private static int inductionDepth;
private static Entity? ByInductionOnAnInequalityCore(Variable x, Set set, Integer least, Entity body, Entity positive, bool strict, bool isExact)
{
var atLeast = body.Substitute(x, least).InnerSimplified(isExact);
if (atLeast is Entity.Boolean)
ProofRecording.AddBelow(body.Substitute(x, least), $"the base case, at {least}, by evaluation", "decide", atLeast);
if (atLeast == Entity.Boolean.False)
return Entity.Boolean.False;
if (atLeast != Entity.Boolean.True)
return null;
// Read off the shape first: 3^(-t - 1) + t^3 is positive on ZZ* term by term.
if (Sign(positive, x, set, isExact) is { } direct && (!strict || direct == Signum.Positive))
return Entity.Boolean.True;
var next = positive.Substitute(x, x + Integer.One);
foreach (var c in Multipliers(positive, x))
{
var tried = ProofRecording.Mark();
if (Sign(c, x, set, isExact) is { } multiplier
&& Sign(Collected(next - c * positive), x, set, isExact) is { } remainder
&& (!strict || multiplier == Signum.Positive || remainder == Signum.Positive))
return Entity.Boolean.True;
ProofRecording.Rollback(tried);
}
return null;
}
/// <summary>The multipliers tried for the step: one, the whole base of each exponential in <paramref name="x"/>, and <c>x + 1</c> beside a factorial.</summary>
private static IEnumerable<Entity> Multipliers(Entity positive, Variable x)
{
yield return Integer.One;
foreach (var @base in positive.Nodes.OfType<Powf>().Where(p => p.Exponent.ContainsNode(x)).Select(p => p.Base).Where(b => b.Evaled is Integer).Distinct())
yield return @base;
if (positive.Nodes.Any(node => node is Factorialf f && f.ContainsNode(x)))
yield return x + Integer.One;
}
/// <summary>
/// The expression as a polynomial over its atoms, collected: <c>3^(x + 1) - 3 * 3^x</c> is
/// <c>0</c>, <c>(x + 1)! - (x + 1) x!</c> is <c>0</c>, <c>2^(x + 1) - 2^x</c> is <c>2^x</c>.
/// </summary>
private static Entity Collected(Entity expr)
{
var atoms = new Dictionary<Entity, Variable>();
var atomized = Atomized(expr.InnerSimplified, atoms, FactorialsUnfolded(expr.InnerSimplified));
var variables = atomized.Vars.OrderBy(v => v.Name, System.StringComparer.Ordinal).ToArray();
var indices = new Dictionary<Variable, int>();
for (var i = 0; i < variables.Length; i++)
indices[variables[i]] = i;
var collected = variables.Length <= MultivariatePolynomial.MaxVariables && MultivariatePolynomial.TryParse(atomized, indices) is { } polynomial
? polynomial.ToEntity(variables)
: atomized;
foreach (var pair in atoms)
collected = collected.Substitute(pair.Value, pair.Key);
return collected.InnerSimplified;
}
private enum Signum { Positive, NonNegative }
/// <summary>
/// Whether the expression is positive, or non-negative, at every member of the set, read
/// off its shape: a positive base to any power, a factorial of a whole number, sums and
/// products of these, and a polynomial in <paramref name="x"/> decided over the set.
/// <see langword="null"/> where neither is known.
/// </summary>
private static Signum? Sign(Entity expr, Variable x, Set set, bool isExact)
{
switch (expr)
{
case Real real:
return real.IsPositive ? Signum.Positive : real.IsNegative ? null : Signum.NonNegative;
case Number:
return null;
case Variable v when v == x:
return LeastMember(set) is { } least ? least.IsPositive ? Signum.Positive : least.IsNegative ? null : Signum.NonNegative : null;
case Sumf(var a, var b):
return (Sign(a, x, set, isExact), Sign(b, x, set, isExact)) switch
{
(null, _) or (_, null) => SignByAtoms(expr, x, set, isExact),
(Signum.Positive, _) or (_, Signum.Positive) => Signum.Positive,
_ => Signum.NonNegative,
};
case Minusf:
return SignOfPolynomial(expr, x, set, isExact) ?? SignByAtoms(expr, x, set, isExact);
case Mulf(var a, var b):
return (Sign(a, x, set, isExact), Sign(b, x, set, isExact)) switch
{
(null, _) or (_, null) => null,
(Signum.Positive, Signum.Positive) => Signum.Positive,
_ => Signum.NonNegative,
};
case Divf(var a, var b):
return (Sign(a, x, set, isExact), Sign(b, x, set, isExact)) switch
{
(null, _) or (_, null) or (_, Signum.NonNegative) => null,
(Signum.Positive, Signum.Positive) => Signum.Positive,
_ => Signum.NonNegative,
};
// A positive base to any real power; the exponent is real where it mentions
// nothing but x, which ranges over whole numbers.
case Powf(var @base, var exponent) when exponent.Vars.All(v => v == x):
return Sign(@base, x, set, isExact) switch
{
Signum.Positive => Signum.Positive,
Signum.NonNegative when exponent.Evaled is Integer { IsNegative: false } => Signum.NonNegative,
_ => exponent.Evaled is Integer { EInteger.IsEven: true } && @base.Vars.All(v => v == x) ? Signum.NonNegative : null,
};
case Factorialf(var argument) when argument.Vars.All(v => v == x) && IsWholePolynomial(argument):
return Sign(argument, x, set, isExact) is not null ? Signum.Positive : null;
default:
return SignOfPolynomial(expr, x, set, isExact);
}
}
/// <summary>
/// A polynomial in <paramref name="x"/> and nothing else, decided over the set by the
/// routes that read one, which do not come back here; <see langword="null"/> for anything else.
/// </summary>
private static Signum? SignOfPolynomial(Entity expr, Variable x, Set set, bool isExact)
{
if (!expr.Vars.All(v => v == x) || !expr.Vars.Any() || MultivariatePolynomial.TryParse(expr, new Dictionary<Variable, int> { [x] = 0 }) is null)
return null;
var tried = ProofRecording.Mark();
if (Decide(Kind.All, x, set, new Greaterf(expr, Integer.Zero).InnerSimplified(isExact), isExact) is Entity.Boolean(true))
return Signum.Positive;
ProofRecording.Rollback(tried);
if (Decide(Kind.All, x, set, new GreaterOrEqualf(expr, Integer.Zero).InnerSimplified(isExact), isExact) is Entity.Boolean(true))
return Signum.NonNegative;
ProofRecording.Rollback(tried);
return null;
}
/// <summary>
/// The sign of a sum read term by term: each term is a product of atoms -- exponentials
/// and factorials in <paramref name="x"/> -- times a polynomial in <paramref name="x"/>,
/// the polynomials are collected per atom product, and the sum is non-negative where
/// every atom product and its collected coefficient are: <c>(n + 1) n! - 2 n!</c> is
/// <c>(n - 1) n!</c>, non-negative on <c>ZZ+</c>.
/// </summary>
private static Signum? SignByAtoms(Entity expr, Variable x, Set set, bool isExact)
{
var groups = new Dictionary<Entity, Entity>();
foreach (var term in Sumf.LinearChildren(expr))
{
Entity atomic = Integer.One;
Entity coefficient = Integer.One;
foreach (var factor in Mulf.LinearChildren(term))
if (factor.Vars.All(v => v == x) && MultivariatePolynomial.TryParse(factor, new Dictionary<Variable, int> { [x] = 0 }) is not null)
coefficient *= factor;
else
atomic *= factor;
atomic = atomic.InnerSimplified;
groups[atomic] = groups.TryGetValue(atomic, out var sum) ? sum + coefficient : coefficient;
}
if (groups.Count < 2 && expr is not Minusf)
return null;
var result = Signum.NonNegative;
foreach (var pair in groups)
{
var atomSign = pair.Key == Integer.One ? Signum.Positive : Sign(pair.Key, x, set, isExact);
var collected = pair.Value.InnerSimplified;
var coefficientSign = collected is Number ? Sign(collected, x, set, isExact) : SignOfPolynomial(collected, x, set, isExact);
if (atomSign is null || coefficientSign is null)
return null;
if (atomSign == Signum.Positive && coefficientSign == Signum.Positive)
result = Signum.Positive;
}
return result;
}
/// <summary>
/// The condition under which a decision is <see langword="true"/> -- <c>True</c> for
/// <c>True</c> itself, the predicate for <c>True provided P</c> -- or
/// <see langword="null"/> for anything else.
/// </summary>
private static Entity? Truth(Entity? decision)
=> decision switch
{
Entity.Boolean(true) => Entity.Boolean.True,
Providedf(Entity.Boolean(true), var predicate) => predicate,
_ => null,
};
internal static bool IsIntegerSet(SpecialSet set)
=> set.ToDomain() is Domain.Integer or Domain.NonNegativeInteger or Domain.PositiveInteger;
/// <summary>How many residues a periodic statement is checked over before it is left as written.</summary>
private const int LargestPeriod = 4096;
/// <summary>
/// The period of the body in <paramref name="x"/> over the whole numbers, where it has
/// one: a divisibility by a whole number, or a congruence modulo one, of polynomials
/// with whole coefficients, joined by the connectives; the least common multiple of the
/// parts' periods.
/// </summary>
private static EInteger? Period(Entity body, Variable x, SpecialSet set)
{
switch (body)
{
case Entity.Boolean:
return EInteger.One;
case Dividesf(Integer divisor, var dividend):
return divisor.EInteger.IsZero ? null : PeriodModulo(dividend, divisor.EInteger.Abs(), x, set);
case Congruentf(var left, var right, Integer modulus):
return modulus.EInteger.IsZero ? null : PeriodModulo(left - right, modulus.EInteger.Abs(), x, set);
case Notf(var operand):
return Period(operand, x, set);
// A quantifier over whole numbers inside: its body is periodic in x with the
// same period whatever the inner name takes, so the residues of x decide the
// outer statement and the inner one is decided at each of them.
case Quantifier { Over: SpecialSet inner } quantifier when IsIntegerSet(inner):
return Period(quantifier.Body, x, set);
case Andf or Orf or Impliesf or Xorf:
if (body is not IBinaryNode { NodeFirstChild: var first, NodeSecondChild: var second })
return null;
if (Period(first, x, set) is not { } one || Period(second, x, set) is not { } another)
return null;
return one * another / one.Gcd(another);
// An equation or an order comparison between residues -- a^7 mod 7 = a mod 7,
// Fermat's little theorem as Sullivan and Mackey write it (Prob 8.9.26) -- repeats
// with the least common multiple of the moduli it mentions.
case Equalsf or Greaterf or GreaterOrEqualf or Lessf or LessOrEqualf:
if (body is not IBinaryNode { NodeFirstChild: var lhs, NodeSecondChild: var rhs })
return null;
// Floors and ceilings of linear functions beside a linear part, where the
// drifts cancel: floor(n/2) + ceil(n/2) - n repeats with 2.
if (DriftlessPeriod(lhs - rhs, x) is { } rounding)
return rounding;
if (ResiduePeriod(lhs, x, set) is not { } l || ResiduePeriod(rhs, x, set) is not { } r)
return null;
return l * r / l.Gcd(r);
default:
return body.ContainsNode(x) ? null : EInteger.One;
}
}
/// <summary>
/// For a body that asks about the members satisfying conditions on the name alone --
/// <c>Q implies P</c> of every member, <c>Q and P</c> of some -- the set cut down by the
/// conjuncts of <c>Q</c> the solver states as a set, where the cut comes out listed or as
/// the whole numbers from a least one; with those conjuncts, and the claim that is left:
/// <c>(0 < k and k < 7 and 2 divides k) implies P</c> is <c>2 divides k implies P</c> over
/// <c>{1, ..., 6}</c>.
/// </summary>
private static (Set Cut, Entity Condition, Entity Claim)? CutByHypothesis(Kind kind, Variable x, SpecialSet set, Entity body, bool isExact)
{
var (hypotheses, conclusion) = (kind, body) switch
{
(Kind.All, Impliesf(var assumption, var then)) => (Andf.LinearChildren(assumption).ToList(), then),
(_, Andf) when kind != Kind.All => (Andf.LinearChildren(body).ToList(), (Entity?)null),
_ => (null, null),
};
if (hypotheses is null)
return null;
var bounds = hypotheses.Where(h => OnlyAbout(h, x) && SolverReads(h, x)).ToList();
var others = hypotheses.Where(h => !bounds.Contains(h)).ToList();
if (bounds.Count == 0)
return null;
var condition = bounds.Aggregate(static (a, b) => a & b);
var claim = kind == Kind.All
? others.Count == 0 ? conclusion! : others.Aggregate(static (a, b) => a & b).Implies(conclusion!)
: others.Count == 0 ? Entity.Boolean.True : others.Aggregate(static (a, b) => a & b);
if (Algebra.AnalyticalSolving.StatementSolver.Solved(condition, x) is not { } solved)
return null;
return new Intersectionf(set, solved).InnerSimplified(isExact) switch
{
FiniteSet listed => (listed, condition, claim),
Intersectionf fromLeast when LeastMember(fromLeast) is not null && IsUnboundedAbove(fromLeast) => (fromLeast, condition, claim),
_ => null,
};
}
private static bool OnlyAbout(Entity condition, Variable x)
=> condition.ContainsNode(x) && condition.Vars.All(v => v == x);
/// <summary>
/// The period in <paramref name="x"/> of an expression made of residues <c>p mod m</c>
/// and numbers by sums, differences and products: <see cref="PeriodModulo"/>'s for each
/// residue, since <c>mod</c> is the floored remainder and <c>p(x) mod m</c> depends on
/// <c>x</c> only through <c>p(x)</c> modulo <c>m</c>; <see langword="null"/> where
/// <paramref name="x"/> appears outside a residue.
/// </summary>
private static EInteger? ResiduePeriod(Entity expr, Variable x, SpecialSet set)
{
if (!expr.ContainsNode(x))
return EInteger.One;
switch (expr)
{
case Modf(var dividend, Integer modulus) when !modulus.EInteger.IsZero:
return PeriodModulo(dividend, modulus.EInteger.Abs(), x, set);
case Sumf or Minusf or Mulf:
if (expr is not IBinaryNode { NodeFirstChild: var first, NodeSecondChild: var second })
return null;
if (ResiduePeriod(first, x, set) is not { } one || ResiduePeriod(second, x, set) is not { } another)
return null;
return one * another / one.Gcd(another);
default:
return null;
}
}
/// <summary>
/// The period of a sum of floors and ceilings of linear functions of <paramref name="x"/>
/// and of a linear part, where the drifts cancel, or <see langword="null"/>. A floor of
/// <c>(p/q) x + b</c> rises by <c>p</c> when <c>x</c> rises by <c>q</c>, and a linear
/// term by its slope times <c>q</c>, so where these sum to nothing the difference repeats
/// with the least common multiple of the <c>q</c>: <c>floor(n/2) + ceil(n/2) - n</c> with
/// 2, and Hermite's <c>floor(n/3) + floor((n + 1)/3) + floor((n + 2)/3) - n</c> with 3.
/// https://github.com/asc-community/AngouriMath/issues/1409
/// </summary>
private static EInteger? DriftlessPeriod(Entity difference, Variable x)
{
var period = EInteger.One;
var drift = ERational.Zero;
var rounded = false;
foreach (var term in Sumf.LinearChildren(difference))
{
if (!term.ContainsNode(x))
continue;
var (coefficient, core) = term is Mulf(Rational factor, var rest) ? (factor.ERational, rest) : (ERational.One, term);
var argument = core switch
{
Floorf floor => floor.Argument,
Ceilf ceiling => ceiling.Argument,
_ => null,
};
if (Slope(argument ?? core, x) is not { } slope)
return null;
if (argument is not null)
{
rounded = true;
var q = slope.Denominator.Abs();
period = period * q / period.Gcd(q);
}
drift = drift.Add(coefficient.Multiply(slope));
}
return rounded && drift.IsZero ? period : null;
}
/// <summary>The slope of an expression linear in <paramref name="x"/> with a rational one, or <see langword="null"/>.</summary>
private static ERational? Slope(Entity expression, Variable x)
=> TreeAnalyzer.TryGetPolyLinear(expression, x, out var a, out var b) && !b.ContainsNode(x) && a.Evaled is Rational rate
? rate.ERational
: null;
/// <summary>
/// The period, in <paramref name="x"/>, of an expression's residue modulo
/// <paramref name="modulus"/>: the modulus for a polynomial with whole coefficients,
/// and with a power <c>a^e</c> of a whole base coprime to the modulus among the terms --
/// <c>7^n - 4^n</c> modulo <c>3</c>, <c>2^n + 1</c> modulo <c>7</c> -- the least common
/// multiple with the order of each base, since <c>a^(e + k) = a^e</c> modulo <c>m</c>
/// where <c>a^k = 1</c>. Over the non-negative whole numbers only, where the powers are
/// whole; <see langword="null"/> for a base sharing a factor with the modulus, whose
/// powers repeat only eventually. Sullivan and Mackey's Ex 5.3.7 and §5.2.4 Try 3.
/// </summary>
private static EInteger? PeriodModulo(Entity expr, EInteger modulus, Variable x, SpecialSet set)
{
if (IsWholePolynomial(expr))
return modulus;
if (set.ToDomain() is not (Domain.NonNegativeInteger or Domain.PositiveInteger))
return null;
var period = modulus;
var replaced = expr;
var count = 0;
foreach (var power in expr.Nodes.OfType<Powf>().Where(p => p.Exponent.ContainsNode(x)).Distinct())
{
if (power.Base.Evaled is not Integer { EInteger: var @base } || !power.Exponent.Vars.All(v => v == x) || !IsWholePolynomial(power.Exponent))
return null;
if (!@base.Gcd(modulus).Equals(EInteger.One))
return null;
var order = EInteger.One;
var value = @base.Mod(modulus);
while (!value.Equals(EInteger.One) && order.CompareTo(modulus) < 0)
{
value = value * @base % modulus;
order += 1;
}
if (!value.Equals(EInteger.One))
return null;
period = period * order / period.Gcd(order);
replaced = replaced.Substitute(power, Variable.CreateUnique(expr, "power_" + count++));
}
return IsWholePolynomial(replaced) ? period : null;
}
/// <summary>
/// A polynomial with whole coefficients in whatever names it mentions -- which is
/// periodic in each of them modulo anything, as long as the others stand for whole
/// numbers.
/// </summary>
private static bool IsWholePolynomial(Entity expression)
{
if (!expression.Vars.Any())
return expression.Evaled is Integer;
var variables = expression.Vars.OrderBy(v => v.Name, System.StringComparer.Ordinal).ToArray();
if (variables.Length > MultivariatePolynomial.MaxVariables)
return false;
var indices = new Dictionary<Variable, int>();
for (var i = 0; i < variables.Length; i++)
indices[variables[i]] = i;
return MultivariatePolynomial.TryParse(expression, indices) is { HasIntegerCoefficients: true };
}
/// <summary>The statement at each residue, which is at every member of the set.</summary>
private static Entity? OverResidues(Kind kind, Variable x, SpecialSet set, Entity body, EInteger period, bool isExact)
{
int holds = 0, fails = 0, undecided = 0;
// From 1 for the positive whole numbers, since 0 is not one; either way every class
// is represented once.
var first = set.ToDomain() == Domain.PositiveInteger ? EInteger.One : EInteger.Zero;
for (var residue = first; residue.CompareTo(first + period) < 0; residue += 1)
switch (body.Substitute(x, Integer.Create(residue)).InnerSimplified(isExact))
{
case Entity.Boolean(true): holds++; break;
case Entity.Boolean(false): fails++; break;
default: undecided++; break;
}
return Tally(kind, holds, fails, undecided, distinct: true);
}
[ConstantField]
private static readonly int[] ModuliTried = { 2, 3, 4, 5, 7, 8, 9, 11, 13, 16 };
/// <summary>
/// <c>exists x, y, ... in ZZ : P = Q</c> is false where the equation has no solution
/// modulo some small <c>m</c>, and <c>forall ... : not (P = Q)</c> true. The variables
/// are the whole chain of quantifiers over whole numbers the body opens with.
/// </summary>
private static Entity? ImpossibleByResidues(Kind kind, Variable x, SpecialSet set, Entity body)
{
var variables = new List<Variable> { x };
var inner = body;
while (true)
{
Variable? next = null;
Entity? deeper = null;
if (kind == Kind.Some && inner is Existsf(Variable some, SpecialSet someOver, var someBody) && IsIntegerSet(someOver))
(next, deeper) = (some, someBody);
else if (kind == Kind.All && inner is Forallf(Variable every, SpecialSet everyOver, var everyBody) && IsIntegerSet(everyOver))
(next, deeper) = (every, everyBody);
if (next is null || deeper is null)
break;
variables.Add(next);
inner = deeper;
}
var equation = kind == Kind.Some ? inner : inner is Notf(var negated) ? negated : null;
if (equation is not Equalsf(var left, var right))
return null;
var difference = (left - right).InnerSimplified;