Repository navigation
Expand file tree
/
Copy pathIntegralPatterns.cs
More file actions
1961 lines (1825 loc) · 116 KB
/
Copy pathIntegralPatterns.cs
File metadata and controls
1961 lines (1825 loc) · 116 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-2022 Angouri.
// AngouriMath is licensed under MIT.
// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.
// Website: https://am.angouri.org.
//
using PeterO.Numbers;
namespace AngouriMath.Functions.Algebra
{
internal static class IntegralPatterns
{
/// <summary>
/// The logarithm an antiderivative of <c>f'/f</c> is written with: <c>ln(abs(f))</c> when
/// the codomain is the reals, <c>ln(f)</c> when it is the complex plane.
/// </summary>
/// <remarks>
/// <para>
/// <c>ln(abs(f))</c> is an antiderivative of <c>f'/f</c> only on the real line. <c>abs</c>
/// is not holomorphic, so off the real line the textbook form is not an antiderivative of
/// anything -- differentiating it does not return the integrand. That is
/// https://github.com/asc-community/AngouriMath/issues/946, and separating by codomain is
/// the answer given there.
/// </para>
/// <para>
/// Under <see cref="AngouriMath.Core.Domain.Real"/> this returns exactly what the table
/// returned before, so a caller who has said they are working on the reals sees no change.
/// The default codomain is the complex plane, so the default answer does change --
/// recorded in <c>BREAKING-CHANGES.md</c>.
/// </para>
/// <para>
/// This is for an <c>abs</c> the rule <i>introduces</i>. Where the integrand already
/// carries one -- the rule for <c>ln(abs(ax + b))</c> below -- the <c>abs</c> in the
/// result is the caller's own and is left alone.
/// </para>
/// </remarks>
internal static Entity AntiderivativeLog(Entity arg)
=> MathS.Settings.Codomain.Value is AngouriMath.Core.Domain.Real
? MathS.Ln(MathS.Abs(arg))
: MathS.Ln(arg);
/// <summary>
/// The argument through which each rule below reads its integrand's dependence on
/// <paramref name="x"/>, or <see langword="null"/> for a shape none of them matches.
/// </summary>
/// <remarks>
/// The conditions on the two two-argument nodes are the ones their own rules carry:
/// a base that mentions <c>x</c> is a different integral, not this one.
/// </remarks>
private static Entity? RateBearingArgument(Entity expr, Entity.Variable x) => expr switch
{
Entity.Sinf(var arg) => arg,
Entity.Cosf(var arg) => arg,
Entity.Secantf(var arg) => arg,
Entity.Cosecantf(var arg) => arg,
Entity.Tanf(var arg) => arg,
Entity.Cotanf(var arg) => arg,
Entity.Absf(var arg) => arg,
Entity.Signumf(var arg) => arg,
Entity.Erff(var arg) => arg,
Entity.Erfcf(var arg) => arg,
Entity.Erfif(var arg) => arg,
Entity.Eif(var arg) => arg,
Entity.Lif(var arg) => arg,
Entity.Sif(var arg) => arg,
Entity.Cif(var arg) => arg,
Entity.Shif(var arg) => arg,
Entity.Chif(var arg) => arg,
Entity.Polygammaf(var order, var arg) when !order.ContainsNode(x) => arg,
Entity.IncompleteGammaf(var order, var arg) when !order.ContainsNode(x) => arg,
Entity.Arcsinf(var arg) => arg,
Entity.Arccosf(var arg) => arg,
Entity.Arctanf(var arg) => arg,
Entity.Arccotanf(var arg) => arg,
Entity.Logf(var @base, var arg) when !@base.ContainsNode(x) => arg,
Entity.Powf(var @base, var power) when !@base.ContainsNode(x) => power,
_ => null
};
/// <summary>
/// <c>int F^(a x^2 + b x + c) dx</c> for a non-zero <c>a</c>: the square completed is
/// <c>a (x + b/(2a))^2 + c - b^2/(4a)</c>, so the integral is <c>F^(c - b^2/(4a))</c> times
/// the Gaussian of <c>A = a ln F</c> in <c>u = x + b/(2a)</c>.
/// </summary>
private static Entity Gaussian(Entity @base, Entity a, Entity b, Entity c, Entity.Variable x)
{
// Built without the terms a zero linear part would contribute: b/(2a) is 0 only
// provided a is not zero, and that condition, stated twice over, was all a symbolic
// F^(a x^2) got for it. The answer is for the generic case, as F^(a x)/(a ln F) is.
if (TreeAnalyzer.IsZero(b))
return MathS.Pow(@base, c) * UnitGaussian(a * MathS.Ln(@base), x);
return MathS.Pow(@base, c - b * b / (4 * a)) * UnitGaussian(a * MathS.Ln(@base), x + b / (2 * a));
}
/// <summary>
/// <c>int P(x) F^(a x^2 + b x + c) dx</c> for a non-zero <c>a</c> and a polynomial <c>P</c>,
/// which may be absent: the Gaussian, or the sum of its moments at the square's centre.
/// </summary>
internal static Entity? APolynomialTimesTheGaussian(Entity? polynomial, Entity @base, Entity a, Entity b, Entity c, Entity.Variable x)
=> polynomial is null
? Gaussian(@base, a, b, c, x)
: ShiftedMoments(Entity.Number.Integer.One, 0, polynomial, @base, a, b, c, x);
/// <summary>
/// <c>int P(x) F^(a x^2 + c) dx</c> for a non-zero <c>a</c>, with <c>P</c> read into
/// <paramref name="powers"/>, each power of <c>x</c> with its coefficient: the moments
/// about 0, where a negative even power is a moment too, and a negative odd one, which
/// ends at the exponential integral, is declined. Asked with no linear term, whose shift
/// <c>b/(2a)</c> would be <c>0/(2a)</c>, which simplifies to <c>0</c> provided <c>a</c> is
/// not 0, and is not read as zero where it is substituted.
/// </summary>
internal static Entity? MomentsAboutZero(Dictionary<EInteger, Entity> powers, Entity @base, Entity a, Entity c, Entity.Variable x)
{
var A = a * MathS.Ln(@base);
var bell = MathS.Pow(@base, a * MathS.Sqr(x));
Entity sum = Entity.Number.Integer.Zero;
foreach (var power in powers)
{
if (!power.Key.CanFitInInt32())
return null;
var k = power.Key.ToInt32Checked();
if (k < 0 && k % 2 != 0 || System.Math.Abs(k) > 32)
return null;
sum += power.Value * Moment(k, A, bell, x);
}
return MathS.Pow(@base, c) * sum;
}
/// <summary>
/// <c>int e^(A u^2) du</c> for a non-zero <c>A</c>: <c>sqrt(pi)/(2 sqrt(-A)) erf(sqrt(-A) u)</c>,
/// or with <c>erfi</c> and the real root where <c>A</c> is decidably positive.
/// </summary>
/// <remarks>
/// The sign is read from <c>Evaled</c>, as the integrator's other sign tests are; they move
/// together to the interval evaluation of https://github.com/asc-community/AngouriMath/pull/1497.
/// Finiteness is asked as well, because <see cref="Entity.Number.Real.IsPositive"/> holds
/// for <c>NaN</c> and <c>+oo</c>.
/// </remarks>
private static Entity UnitGaussian(Entity A, Entity u)
=> A.Evaled is Entity.Number.Real { EDecimal.IsFinite: true, IsPositive: true }
? MathS.Sqrt(MathS.pi) / (2 * MathS.Sqrt(A)) * MathS.Erfi(MathS.Sqrt(A) * u)
: MathS.Sqrt(MathS.pi) / (2 * MathS.Sqrt(-A)) * MathS.Erf(MathS.Sqrt(-A) * u);
/// <summary>
/// <c>int k x^m F^(a x^2 + c) dx</c> for a whole <c>m</c>, not zero, and a non-zero <c>a</c>: the
/// Gaussian moments. With <c>A = a ln F</c> and <c>I_m</c> the integral of
/// <c>x^m e^(A x^2)</c>, parts give <c>I_m = x^(m - 1) e^(A x^2)/(2A) - (m - 1)/(2A) I_(m - 2)</c>,
/// and read the other way <c>I_m = x^(m + 1) e^(A x^2)/(m + 1) - 2A/(m + 1) I_(m + 2)</c> for a
/// negative <c>m</c>, each two powers nearer the Gaussian <c>I_0</c>. An odd positive <c>m</c>
/// ends at <c>I_1 = e^(A x^2)/(2A)</c>, which is elementary and answered elsewhere, and an odd
/// negative one at <c>I_(-1) = Ei(A x^2)/2</c>.
/// https://github.com/asc-community/AngouriMath/issues/1501
/// </summary>
private static Entity? GaussianMoment(Entity expr, Entity.Variable x)
{
// Asked of every integrand that reaches the table, so a type test comes first, and
// nothing here captures a local: a closure is allocated on entry, before any return.
if (expr is not (Entity.Mulf or Entity.Divf))
return null;
var (numerator, denominator) = expr is Entity.Divf(var n, var d) ? (n, d) : (expr, (Entity)Entity.Number.Integer.One);
Entity coefficient = Entity.Number.Integer.One;
int? power = null;
Entity.Powf? gaussian = null;
Entity? polynomial = null;
foreach (var factor in Entity.Mulf.LinearChildren(numerator))
if (!TakeMomentFactor(factor, inverted: false, x, ref coefficient, ref power, ref gaussian, ref polynomial))
return null;
foreach (var factor in Entity.Mulf.LinearChildren(denominator))
if (!TakeMomentFactor(factor, inverted: true, x, ref coefficient, ref power, ref gaussian, ref polynomial))
return null;
if (gaussian is null || !TreeAnalyzer.TryGetPolyQuadratic(gaussian.Exponent, x, out var a, out var b, out var c) || TreeAnalyzer.IsZero(a))
return null;
// A linear term: every whole power beside it, and a polynomial, at the square's centre.
// Without one, a polynomial beside the Gaussian is a sum the integrator splits first.
if (!TreeAnalyzer.IsZero(b))
return ShiftedMoments(coefficient, power ?? 0, polynomial, gaussian.Base, a, b, c, x);
// An odd positive power is elementary, and answered elsewhere; an odd negative one ends
// at the exponential integral.
if (polynomial is not null || power is not { } m || m == 0 || m > 0 && m % 2 != 0 || System.Math.Abs(m) > 32)
return null;
var bell = MathS.Pow(gaussian.Base, a * MathS.Sqr(x));
return coefficient * MathS.Pow(gaussian.Base, c) * Moment(m, a * MathS.Ln(gaussian.Base), bell, x);
}
/// <summary>
/// <c>int k x^m P(x) F^(a x^2 + b x + c) dx</c> with a linear term <c>b</c>, for a whole
/// <c>m</c> and a polynomial <c>P</c>, which may be absent. At the square's centre,
/// <c>u = x + b/(2a)</c>, the exponential is <c>F^(c - b^2/(4a))</c> times <c>F^(a u^2)</c>,
/// and <c>x^m P(x)</c> a polynomial in <c>u</c>, each power of which is a moment of the
/// Gaussian. An odd moment ends at <c>I_1 = e^(A u^2)/(2A)</c>, which is elementary.
/// Rubi's 2.3, <c>f^(a + b x + c x^2) (d + e x)^m</c> and <c>f^(c (a + b x)^2) x^m</c>.
/// https://github.com/asc-community/AngouriMath/issues/1501
/// </summary>
private static Entity? ShiftedMoments(Entity coefficient, int power, Entity? polynomial, Entity @base, Entity a, Entity b, Entity c, Entity.Variable x)
{
if (power < 0 || power > 32)
return null;
var shift = (b / (2 * a)).InnerSimplified;
var u = Entity.Variable.CreateUnique(@base + a + b + c + x, "u");
Entity inX = power == 0 ? Entity.Number.Integer.One : MathS.Pow(x, power);
if (polynomial is not null)
inX *= polynomial;
if (!TreeAnalyzer.TryGetPolynomial(inX.Substitute(x, u - shift), u, out var monomials)
|| monomials.Keys.Any(k => k.Sign < 0 || k.CompareTo(EInteger.FromInt32(32)) > 0))
return null;
var A = a * MathS.Ln(@base);
var bell = MathS.Pow(@base, a * MathS.Sqr(u));
Entity sum = Entity.Number.Integer.Zero;
foreach (var monomial in monomials)
sum += monomial.Value * Moment(monomial.Key.ToInt32Checked(), A, bell, u);
return coefficient * MathS.Pow(@base, c - b * b / (4 * a)) * sum.Substitute(u, x + shift);
}
/// <summary>
/// Reads one factor of a Gaussian moment into the constant coefficient, the power of
/// <paramref name="x"/> or the exponential, and says whether it was one of the three.
/// </summary>
private static bool TakeMomentFactor(Entity factor, bool inverted, Entity.Variable x,
ref Entity coefficient, ref int? power, ref Entity.Powf? gaussian, ref Entity? polynomial)
{
if (!factor.ContainsNode(x))
{
coefficient = inverted ? coefficient / factor : coefficient * factor;
return true;
}
if (power is null && factor == x)
{
power = inverted ? -1 : 1;
return true;
}
if (power is null && factor is Entity.Powf(var b, Entity.Number.Integer n) && b == x && n.EInteger.CanFitInInt32())
{
power = inverted ? -n.EInteger.ToInt32Checked() : n.EInteger.ToInt32Checked();
return true;
}
// Below the bar too, as the exponential of the negated exponent: `1/(e^(b^2 x^2) x^2)` is
// `e^(-b^2 x^2)/x^2`, and it is how by parts writes the factor beside `erf(b x)` in
// `erf(b x)/(e^(b^2 x^2) x^2)`, which was declined for want of its integral.
// https://github.com/asc-community/AngouriMath/issues/1501
if (gaussian is null && factor is Entity.Powf(var @base, var exponent) exponential && !@base.ContainsNode(x))
{
gaussian = inverted ? new Entity.Powf(@base, -exponent) : exponential;
return true;
}
// A sum, or a whole power of one, taken as it is: read as a polynomial only once a
// Gaussian with a linear term is known to be beside it.
if (!inverted && polynomial is null
&& factor is Entity.Sumf or Entity.Minusf or Entity.Powf(Entity.Sumf or Entity.Minusf, Entity.Number.Integer { EInteger.Sign: > 0 }))
{
polynomial = factor;
return true;
}
return false;
}
/// <summary>
/// <c>I_k</c>, the integral of <c>x^k e^(A x^2)</c>, where <paramref name="bell"/> is that
/// exponential as the integrand writes it: an even <c>k</c> down to the Gaussian, an odd
/// positive one down to the elementary <c>I_1</c>, and an odd negative one up to
/// <c>I_(-1) = Ei(A x^2)/2</c>, the exponential integral under <c>t = x^2</c>.
/// </summary>
private static Entity Moment(int k, Entity A, Entity bell, Entity.Variable x) => k switch
{
0 => UnitGaussian(A, x),
1 => bell / (2 * A),
-1 => MathS.Ei(A * MathS.Sqr(x)) / 2,
> 0 => MathS.Pow(x, k - 1) * bell / (2 * A) + ((1 - k) / (2 * A)).InnerSimplified * Moment(k - 2, A, bell, x),
_ => MathS.Pow(x, k + 1) * bell / (k + 1) + (-2 * A / (k + 1)).InnerSimplified * Moment(k + 2, A, bell, x),
};
/// <summary>
/// <c>int P Gamma(n, u) dx</c> for the upper incomplete gamma function of a linear
/// <c>u = a + b x</c> with <c>n</c> free of <c>x</c>, where <c>P</c> is a polynomial in
/// <c>x</c>, or, without an offset <c>a</c>, a power <c>(d x)^m</c> for any <c>m</c> but -1.
/// By parts against an antiderivative <c>Q</c> of <c>P</c>: the derivative of
/// <c>Gamma(n, u)</c> is <c>-b u^(n - 1) e^(-u)</c>, and with <c>Q</c> written in powers of
/// <c>u</c>, each <c>u^k</c> lands on <c>u^(n + k - 1) e^(-u)</c>, the derivative in <c>u</c>
/// of <c>-Gamma(n + k, u)</c>. Rubi's 8.6.
/// https://github.com/asc-community/AngouriMath/issues/2075
/// </summary>
private static Entity? IncompleteGammaBesideAPower(Entity expr, Entity.Variable x)
{
// Asked of every integrand that reaches the table, so a type test comes first, and
// nothing here captures a local.
if (expr is not (Entity.Mulf or Entity.Divf or Entity.IncompleteGammaf))
return null;
var (numerator, denominator) = expr is Entity.Divf(var n, var d) ? (n, d) : (expr, (Entity)Entity.Number.Integer.One);
Entity coefficient = Entity.Number.Integer.One;
Entity.IncompleteGammaf? gamma = null;
Entity? above = null;
Entity? below = null;
foreach (var factor in Entity.Mulf.LinearChildren(numerator))
if (!factor.ContainsNode(x))
coefficient *= factor;
else if (gamma is null && factor is Entity.IncompleteGammaf incompleteGamma)
gamma = incompleteGamma;
else
above = above is null ? factor : above * factor;
foreach (var factor in Entity.Mulf.LinearChildren(denominator))
if (!factor.ContainsNode(x))
coefficient /= factor;
else if (below is null)
below = factor;
else
return null;
if (gamma is null || gamma.Parameter.ContainsNode(x)
|| !TreeAnalyzer.TryGetPolyLinear(gamma.LowerLimit, x, out var slope, out var offset))
return null;
var withoutAnOffset = TreeAnalyzer.IsZero(offset);
if (below is null && ThePowersOf(above, x, withoutAnOffset ? 100 : 32) is { } inX)
return (withoutAnOffset
? BesideAPolynomialWithoutAnOffset(inX, gamma, slope, x)
: BesideAPolynomial(above ?? Entity.Number.Integer.One, gamma, slope, offset, x)) is { } answer
? coefficient * answer
: null;
if (!withoutAnOffset)
return null;
// A power of a multiple of x, of any exponent but -1, whose integral is not a gamma
// function: x^m Gamma(n, b x) is x^(m + 1) Gamma(n, b x)/(m + 1) - x^m (b x)^(-m)
// Gamma(m + n + 1, b x)/(b (m + 1)), and the quotient x^m/(b x)^m is b^(-m) for a whole m
// only: elsewhere the two powers take their branches separately, and it is constant only
// between the cuts.
Entity written;
Entity @base;
Entity scale;
Entity m;
if (below is null && above is not null && TryReadAPowerOfAMultiple(above, x, out @base, out scale, out m))
written = above;
else if (above is null && below is not null && TryReadAPowerOfAMultiple(below, x, out @base, out scale, out var mBelow))
{
written = 1 / below;
m = (-mBelow).InnerSimplified;
}
else
return null;
var mPlusOne = (m + 1).InnerSimplified;
if (TreeAnalyzer.IsZero(mPlusOne))
return null;
// (d x)^(m + 1)/d, which is (d x)^m x on every branch.
var integrated = @base == x ? MathS.Pow(x, mPlusOne) : MathS.Pow(@base, mPlusOne) / scale;
var shifted = MathS.IncompleteGamma((gamma.Parameter + mPlusOne).InnerSimplified, gamma.LowerLimit);
var quotient = m is Entity.Number.Integer
? MathS.Pow((scale / slope).InnerSimplified, m)
: written * MathS.Pow(gamma.LowerLimit, -m);
return coefficient * (integrated * gamma - quotient * shifted / slope) / mPlusOne;
}
/// <summary>
/// <see cref="APowerBesideAnExponentialOfAPower"/> at a whole or half-whole order too, for
/// the integrator to ask once nothing else has answered: <c>(c + d x)^(-1 - 4 n) F^(a + b (c + d x)^n)</c> is a gamma
/// function of order -4, where the other routes reach to -3.
/// </summary>
internal static Entity? APowerBesideAnExponentialOfAPowerAtAnyOrder(Entity expr, Entity.Variable x) => APowerBesideAnExponentialOfAPower(expr, x, atAnyOrder: true);
/// <summary>
/// <c>int x^m F^(a + b x^n) dx</c>, and <c>int (c + d x)^m F^(a + b x) dx</c>, where the integral is a gamma
/// function of <c>s = (m + 1)/n</c>, for an <c>s</c> neither whole nor half a whole number -- where it is
/// elementary, an exponential integral or an error function, and those are answered as such -- or not a
/// number at all. With <c>z = -b ln(F) x^n</c>, <c>x^(m + 1) z^(-s)</c> is constant between the cuts and
/// <c>Gamma(s, z)</c> differentiates to <c>-z^(s - 1) e^(-z) z'</c>, so the first is
/// <c>-F^a x^(m + 1) z^(-s) Gamma(s, z)/n</c>; the second is the first with <c>n = 1</c> under
/// <c>t = c + d x</c>. Several exponentials are read as one, and terms of one degree in the exponent as one term:
/// <c>f^(a + b x^n) g^(c + d x^n)</c> is <c>e^(a ln f + c ln g + (b ln f + d ln g) x^n)</c>. Rubi's 2.3.
/// https://github.com/asc-community/AngouriMath/issues/2075
/// </summary>
private static Entity? APowerBesideAnExponentialOfAPower(Entity expr, Entity.Variable x, bool atAnyOrder = false)
{
// Asked of every integrand that reaches the table, so a type test comes first, and
// nothing here captures a local.
if (expr is not (Entity.Mulf or Entity.Divf or Entity.Powf))
return null;
var (numerator, denominator) = expr is Entity.Divf(var n, var d) ? (n, d) : (expr, (Entity)Entity.Number.Integer.One);
// The exponentials, read as one: F^u F^v is F^(u + v), and F^u G^v is e^(u ln F + v ln G), as
// f^(a + b x^n) g^(c + d x^n) is.
Entity? exponentialBase = null;
Entity? exponent = null;
Entity? inE = null;
var sameBase = true;
for (var side = 0; side < 2; side++)
foreach (var factor in Entity.Mulf.LinearChildren(side == 0 ? numerator : denominator))
if (factor is Entity.Powf(var @base, var power) && !@base.ContainsNode(x) && power.ContainsNode(x))
{
var signed = side == 0 ? power : -power;
var natural = @base == MathS.e ? signed : MathS.Ln(@base) * signed;
sameBase &= exponentialBase is null || exponentialBase == @base;
exponentialBase ??= @base;
exponent = exponent is null ? signed : exponent + signed;
inE = inE is null ? natural : inE + natural;
}
if (exponentialBase is null || exponent is null || inE is null)
return null;
if (!sameBase)
(exponentialBase, exponent) = (MathS.e, inE);
// What is beside it: constants, and powers of multiples of x, (d x)^m, whose product P has
// P'/P = M/x with M the sum of their exponents -- or one power of a linear with an offset.
Entity coefficient = Entity.Number.Integer.One;
Entity? written = null;
Entity exponents = Entity.Number.Integer.Zero;
var factorsInX = 0;
var allOfX = true;
var allMultiples = true;
Entity? single = null;
Entity? before = null;
var singleBelow = false;
var anyBelow = false;
Entity singleBase = x;
Entity singleScale = Entity.Number.Integer.One;
for (var side = 0; side < 2; side++)
foreach (var factor in Entity.Mulf.LinearChildren(side == 0 ? numerator : denominator))
{
if (factor is Entity.Powf(var exponentialFactorsBase, var power) && !exponentialFactorsBase.ContainsNode(x) && power.ContainsNode(x))
continue;
if (!factor.ContainsNode(x))
{
coefficient = side == 0 ? coefficient * factor : coefficient / factor;
continue;
}
factorsInX++;
before = single;
single = factor;
singleBelow = side == 1;
anyBelow |= side == 1;
if (TryReadAPowerOfAMultiple(factor, x, out var @base, out var scale, out var m))
{
written = written is null ? (side == 0 ? factor : 1 / factor) : side == 0 ? written * factor : written / factor;
exponents = side == 0 ? exponents + m : exponents - m;
allOfX &= @base == x;
singleBase = @base;
singleScale = scale;
}
else
allMultiples = false;
}
var logarithm = exponentialBase == MathS.e ? Entity.Number.Integer.One : MathS.Ln(exponentialBase);
// The exponent as a + b x^n, the term in x as written, or as expanded: -(c + d x^3) is one term as written, and
// it is how sinh(c + d x^3) arrives, as (e^(c + d x^3) - e^(-(c + d x^3)))/2.
Entity constant = Entity.Number.Integer.Zero;
Entity? term = null;
Entity? degree = null;
var collected = 0;
for (var reading = 0; reading < 2 && term is null; reading++)
{
var asRead = reading == 0 ? exponent : exponent.Expand();
if (reading == 1 && asRead == exponent)
break;
constant = Entity.Number.Integer.Zero;
// And terms of one degree as one: b x^n + d x^n is (b + d) x^n.
foreach (var summand in Entity.Sumf.LinearChildren(asRead))
if (!summand.ContainsNode(x))
constant += summand;
else if (ThePowerOfX(summand, x) is { } read && (term is null || read == degree))
{
term = term is null ? summand : term + summand;
degree = read;
collected++;
}
else
{
term = null;
break;
}
}
// Or a linear written otherwise, as the negation -(a + b x) is, which is how gamma(2, a + b x) is
// elementary: e^(-(a + b x)) (1 + a + b x). https://github.com/asc-community/AngouriMath/issues/2075
if (term is null && TreeAnalyzer.TryGetPolyLinear(exponent, x, out var slopeOfTheExponent, out var offsetOfTheExponent)
&& !TreeAnalyzer.IsZero(slopeOfTheExponent))
{
constant = offsetOfTheExponent;
term = (slopeOfTheExponent * x).InnerSimplified;
degree = Entity.Number.Integer.One;
}
if (term is null || degree is null || TreeAnalyzer.IsZero(degree))
return null;
// Terms gathered from two summands or two exponentials can cancel: e^x e^(-x)/x is 1/x, and read as a gamma
// function of order 0 at 0 it was NaN, by parts beside Shi(a + b x)^2. Decided by Simplify, which only the
// gathered ones reach.
if (collected > 1 && !term.Simplify().ContainsNode(x))
return null;
if (allMultiples)
{
var mPlusOne = (exponents + 1).InnerSimplified;
var s = TheOrder(mPlusOne / degree);
if (!atAnyOrder && WholeOrHalfWhole(s))
return null;
// z = k x for a linear exponent, with the rate read as the number it may be.
var linearRate = degree.Equals(Entity.Number.Integer.One) && TreeAnalyzer.TryGetPolyLinear(term, x, out var rateOfTerm, out _)
? (-logarithm * rateOfTerm).InnerSimplified
: null;
var z = linearRate is null ? (-logarithm * term).InnerSimplified : (linearRate * x).InnerSimplified;
var leading = (-coefficient / degree).InnerSimplified * Exponential(exponentialBase, constant);
// For a positive k, x^(m + 1) z^(-s) is k^(-s) on every branch, and for a whole s with any k.
if (linearRate is not null && allOfX && (linearRate is Entity.Number.Real { IsPositive: true } || s is Entity.Number.Integer))
return leading * MathS.Pow(linearRate, (-s).InnerSimplified).InnerSimplified * MathS.IncompleteGamma(s, z);
// P x: x^(M + 1) for powers of x, and (d x)^(m + 1)/d for one power of a multiple.
var integrated = allOfX ? Power(x, mPlusOne)
: factorsInX == 1 ? MathS.Pow(singleBase, mPlusOne) / singleScale
: written! * x;
var constantFactor = integrated * MathS.Pow(z, (-s).InnerSimplified);
// x^(m + 1) z^(-s), constant on each half-line, is K^(-s) for x > 0 with z = K x^n, and its value at -1 for
// x < 0. Where the two are one number it is that number on the whole line, and the answer has a value at 0
// rather than 0 times an infinity there: e^(x^3) is gamma(1/3, -x^3)/3, and its integral from 0 to 1 was NaN.
// The two are its values at 1 and -1, which need not be numbers: x^(1/3) e^(-1 - 3 x^2) has 3^(-2/3) on both.
if (allOfX
&& constantFactor.Substitute(x, Entity.Number.Integer.One).InnerSimplified is var onTheRight
&& !onTheRight.ContainsNode(x)
&& constantFactor.Substitute(x, Entity.Number.Integer.MinusOne).InnerSimplified == onTheRight)
return leading * onTheRight * MathS.IncompleteGamma(s, z);
return leading * constantFactor * MathS.IncompleteGamma(s, z);
}
// And a polynomial beside a power of a linear with an offset, written in powers of the linear, each term then that
// power alone: (c + d x)^m (k + f x) F^(a + b x) is (c + d x)^m ((k d - f c) + f (c + d x))/d F^(a + b x). By
// parts leaves this of (c + d x)^m gamma(2, a + b x).
if (factorsInX == 2 && !anyBelow && before is not null && single is not null && degree.Equals(Entity.Number.Integer.One))
foreach (var (power, polynomial) in new[] { (before, single), (single, before) })
{
if (power is not Entity.Powf(var linearBase, var exponentOfTheLinear) || exponentOfTheLinear.ContainsNode(x)
|| exponentOfTheLinear is Entity.Number.Integer
|| !TreeAnalyzer.TryGetPolyLinear(linearBase, x, out var slopeOfTheLinear, out var offsetOfTheLinear)
|| TreeAnalyzer.IsZero(offsetOfTheLinear)
|| !TreeAnalyzer.TryGetPolynomial(polynomial, x, out var inXsPowers) || inXsPowers.Keys.Any(degreeInX => degreeInX.Sign < 0 || degreeInX.CompareTo(EInteger.FromInt32(8)) > 0))
continue;
var l = Entity.Variable.CreateUnique(expr, "l_linear");
if (!TreeAnalyzer.TryGetPolynomial(polynomial.Substitute(x, (l - offsetOfTheLinear) / slopeOfTheLinear), l, out var inLsPowers))
continue;
Entity? sum = null;
foreach (var termInL in inLsPowers)
{
var (j, q) = (termInL.Key, termInL.Value);
if (TreeAnalyzer.IsZero(q))
continue;
var termOfIt = coefficient * q * MathS.Pow(linearBase, (exponentOfTheLinear + Entity.Number.Integer.Create(j)).InnerSimplified)
* Exponential(exponentialBase, exponent);
if (APowerBesideAnExponentialOfAPower(termOfIt, x, atAnyOrder) is not { } integrated)
return null;
sum = sum is null ? integrated : sum + integrated;
}
return sum;
}
// A power of a linear with an offset, beside an exponential of a linear -- or a power of a power of one,
// ((c + d x)^n)^m, which stands as written where (c + d x)^(n m) would: its logarithmic derivative is
// n m d/(c + d x) on every branch, and that is all the answer asks of it.
if (factorsInX != 1 || !degree.Equals(Entity.Number.Integer.One)
|| single is not Entity.Powf(var linear, var exponentOfLinear) || exponentOfLinear.ContainsNode(x))
return null;
while (linear is Entity.Powf(var innerLinear, var innerExponent) && !innerExponent.ContainsNode(x))
(linear, exponentOfLinear) = (innerLinear, (innerExponent * exponentOfLinear).InnerSimplified);
if (!TreeAnalyzer.TryGetPolyLinear(linear, x, out var slope, out var offset)
|| !TreeAnalyzer.TryGetPolyLinear(term, x, out var rate, out _))
return null;
var exponentOfPower = singleBelow ? (-exponentOfLinear).InnerSimplified : exponentOfLinear;
if (!atAnyOrder && WholeOrHalfWhole(TheOrder(exponentOfPower + 1)))
return null;
var under = (-logarithm * rate * linear / slope).InnerSimplified;
return coefficient * Exponential(exponentialBase, (constant - rate * offset / slope).InnerSimplified) * (singleBelow ? 1 / single : single)
* MathS.Pow(under, -exponentOfPower) * MathS.IncompleteGamma((exponentOfPower + 1).InnerSimplified, under) / (logarithm * rate);
}
/// <summary>
/// <c>int P sin(u)^k cos(u)^j dx</c> for a power <c>P</c> of <c>x</c>, or of a linear, which is not a polynomial -- or
/// none, beside a function of a power of <c>x</c>, <c>sin(a + b x^3)</c>: by
/// Euler's formula <c>sin(u)^k cos(u)^j</c> is a sum of <c>e^(i q u)</c>, each beside <c>P</c> a gamma function of
/// <see cref="APowerBesideAnExponentialOfAPower"/>, and the term with <c>q = 0</c> is <c>P</c>'s own integral. Where any
/// term is declined -- a whole power of <c>x</c>, whose integral is elementary and answered by parts -- so is the
/// integrand. The gamma functions' arguments are imaginary on the real line, off the cut. Rubi's 4.1.10 and 4.1.12.
/// https://github.com/asc-community/AngouriMath/issues/2075
/// </summary>
private static Entity? APowerBesideATrigonometricFunction(Entity expr, Entity.Variable x)
{
// Asked of every integrand that reaches the table, so a type test comes first, and nothing here captures a
// local before it has found a sine or a cosine.
if (expr is not (Entity.Mulf or Entity.Divf or Entity.Sinf or Entity.Cosf or Entity.Powf(Entity.Sinf or Entity.Cosf, _)))
return null;
var (numerator, denominator) = expr is Entity.Divf(var n, var d) ? (n, d) : (expr, (Entity)Entity.Number.Integer.One);
Entity coefficient = Entity.Number.Integer.One;
Entity? argument = null;
var sines = 0;
var cosines = 0;
Entity? above = null;
Entity? below = null;
foreach (var factor in Entity.Mulf.LinearChildren(numerator))
{
if (!factor.ContainsNode(x))
coefficient *= factor;
else if (TheTrigonometricPower(factor) is var (isSine, trigonometricArgument, times)
&& (argument is null || argument == trigonometricArgument))
{
argument = trigonometricArgument;
if (isSine) sines += times; else cosines += times;
}
else
above = above is null ? factor : above * factor;
}
if (argument is null || sines + cosines > 8)
return null;
foreach (var factor in Entity.Mulf.LinearChildren(denominator))
if (!factor.ContainsNode(x))
coefficient /= factor;
else
below = below is null ? factor : below * factor;
// sin(u)^k cos(u)^j = (2 i)^(-k) 2^(-j) sum C(k, r) (-1)^(k - r) C(j, t) e^(i (2 r - k + 2 t - j) u).
var weights = new SortedDictionary<int, EInteger>();
for (var r = 0; r <= sines; r++)
for (var t = 0; t <= cosines; t++)
{
var q = 2 * r - sines + 2 * t - cosines;
var weight = Binomial(sines, r).EInteger.Multiply(Binomial(cosines, t).EInteger);
if ((sines - r) % 2 != 0)
weight = weight.Negate();
weights[q] = weights.TryGetValue(q, out var already) ? already.Add(weight) : weight;
}
Entity sum = Entity.Number.Integer.Zero;
// The highest frequency first: where the power is whole, the gamma rule declines it at once.
foreach (var weight in weights.Reverse())
{
if (weight.Value.IsZero)
continue;
Entity? term;
if (weight.Key == 0)
term = TheIntegralOfAPower(above, below, x);
else
{
var exponential = MathS.Pow(MathS.e, (MathS.i * weight.Key * argument).Expand());
var integrand = above is null ? (below is null ? exponential : exponential / below) : below is null ? above * exponential : above * exponential / below;
term = APowerBesideAnExponentialOfAPower(integrand, x);
}
if (term is null)
return null;
sum += Entity.Number.Integer.Create(weight.Value) * term;
}
return coefficient / (MathS.Pow(2 * MathS.i, sines) * MathS.Pow(2, cosines)) * sum;
}
/// <summary><paramref name="factor"/> as <c>sin(u)^k</c> or <c>cos(u)^k</c> for a whole <c>k >= 1</c>.</summary>
private static (bool IsSine, Entity Argument, int Times)? TheTrigonometricPower(Entity factor) => factor switch
{
Entity.Sinf(var u) => (true, u, 1),
Entity.Cosf(var u) => (false, u, 1),
Entity.Powf(Entity.Sinf(var u), Entity.Number.Integer { EInteger: var k }) when k.Sign > 0 && k.CompareTo(EInteger.FromInt32(8)) <= 0
=> (true, u, k.ToInt32Checked()),
Entity.Powf(Entity.Cosf(var u), Entity.Number.Integer { EInteger: var k }) when k.Sign > 0 && k.CompareTo(EInteger.FromInt32(8)) <= 0
=> (false, u, k.ToInt32Checked()),
_ => null
};
/// <summary>
/// The integral of a power <c>(d x)^m</c> above or below the bar, or of a power <c>(c + d x)^m</c>, for any <c>m</c> but -1,
/// or <see langword="null"/>.
/// </summary>
private static Entity? TheIntegralOfAPower(Entity? above, Entity? below, Entity.Variable x)
{
if (above is null && below is null)
return x;
if (above is not null && below is not null)
return null;
var power = above ?? below!;
Entity @base, m;
if (power == x)
(@base, m) = (x, Entity.Number.Integer.One);
else if (power is Entity.Powf(var written, var exponent) && !exponent.ContainsNode(x))
(@base, m) = (written, exponent);
else
return null;
if (!TreeAnalyzer.TryGetPolyLinear(@base, x, out var slope, out _))
return null;
var mPlusOne = (above is null ? -m + 1 : m + 1).InnerSimplified;
if (TreeAnalyzer.IsZero(mPlusOne))
return null;
return MathS.Pow(@base, mPlusOne) / (slope * mPlusOne);
}
/// <summary>
/// The gamma function's order <paramref name="s"/>, as the number it is where its symbols cancel: <c>(-1 + n + 1)/n</c>
/// is 1, which inner simplification leaves as written, and <c>(p x)^(n - 1) e^(x^n)</c>, whose integral is
/// <c>e^(x^n)/n</c>, was answered as <c>gamma((-1 + n + 1)/n, -x^n)</c>.
/// </summary>
private static Entity TheOrder(Entity s)
{
var inner = s.InnerSimplified;
if (inner is Entity.Number || !inner.Vars.Any())
return inner;
// 1 provided not n = 0, as the integrator answers the generic case.
return inner.Simplify() switch
{
Entity.Number number => number,
Entity.Providedf(Entity.Number number, _) => number,
_ => inner
};
}
/// <summary>
/// Whether <paramref name="s"/> is a number that is whole or half of a whole number, and no more than 30 in size:
/// where the integral is elementary, an exponential integral or an error function, and is answered as such. Past
/// that it is the gamma function, which stays one, where parts or the Gaussian's moments would take as many
/// steps as <c>s</c> and write as many terms: <c>x^100 e^(-a x)</c> is <c>-Gamma(101, a x)/a^101</c>.
/// </summary>
private static bool WholeOrHalfWhole(Entity s)
=> s is Entity.Number.Rational { ERational: var exact }
? exact.Denominator.CompareTo(EInteger.FromInt32(2)) <= 0 && exact.Abs().CompareTo(ERational.FromInt32(30)) <= 0
: s is Entity.Number.Real { EDecimal: var approximate } && approximate.IsFinite && approximate.Multiply(2).IsInteger()
&& approximate.Abs().CompareTo(EDecimal.FromInt32(30)) <= 0;
/// <summary><paramref name="base"/> to <paramref name="power"/>, without a zeroth power.</summary>
private static Entity Exponential(Entity @base, Entity power)
=> TreeAnalyzer.IsZero(power) ? Entity.Number.Integer.One : MathS.Pow(@base, power);
/// <summary>
/// The <c>n</c> of <paramref name="term"/> as <c>b x^n</c>, with <c>b</c> and <c>n</c> free of
/// <paramref name="x"/>, or <see langword="null"/>: each factor in <c>x</c> is <c>x</c>, a power of it, or a whole
/// power of one, which is how a quotient's divisor is read.
/// </summary>
private static Entity? ThePowerOfX(Entity term, Entity.Variable x)
{
Entity? degree = null;
foreach (var factor in Entity.Mulf.LinearChildren(term))
{
if (!factor.ContainsNode(x))
continue;
Entity? read = factor == x ? Entity.Number.Integer.One
: factor is Entity.Powf(var @base, var power) && !power.ContainsNode(x)
? (@base == x ? power
: @base is Entity.Powf(var inner, var innerPower) && inner == x && !innerPower.ContainsNode(x) && power is Entity.Number.Integer
? innerPower * power
: null)
: null;
if (read is null)
return null;
degree = degree is null ? read : degree + read;
}
return degree?.InnerSimplified;
}
/// <summary>
/// <paramref name="polynomial"/>'s coefficients by power of <paramref name="x"/>, with
/// <see langword="null"/> read as 1, or <see langword="null"/> where it is not a polynomial
/// of a degree from 0 to <paramref name="highest"/>.
/// </summary>
private static Dictionary<EInteger, Entity>? ThePowersOf(Entity? polynomial, Entity.Variable x, int highest)
{
if (polynomial is null)
return new Dictionary<EInteger, Entity> { [EInteger.Zero] = Entity.Number.Integer.One };
if (!TreeAnalyzer.TryGetPolynomial(polynomial, x, out var powers))
return null;
foreach (var power in powers.Keys)
if (power.Sign < 0 || power.CompareTo(EInteger.FromInt32(highest)) > 0)
return null;
return powers;
}
/// <summary>
/// <c>int P(x) Gamma(n, b x) dx</c> for <c>P</c> read into <paramref name="powers"/>: each
/// <c>c x^j</c> is <c>c (x^(j + 1) Gamma(n, b x) - Gamma(n + j + 1, b x)/b^(j + 1))/(j + 1)</c>.
/// </summary>
private static Entity BesideAPolynomialWithoutAnOffset(Dictionary<EInteger, Entity> powers, Entity.IncompleteGammaf gamma, Entity slope, Entity.Variable x)
{
Entity antiderivative = Entity.Number.Integer.Zero;
Entity shifted = Entity.Number.Integer.Zero;
foreach (var monomial in powers)
{
var next = Entity.Number.Integer.Create(monomial.Key.Add(1));
antiderivative += monomial.Value * Power(x, next.EInteger.ToInt32Checked()) / next;
shifted += (monomial.Value / (next * Power(slope, next.EInteger.ToInt32Checked()))).InnerSimplified
* MathS.IncompleteGamma((gamma.Parameter + next).InnerSimplified, gamma.LowerLimit);
}
return antiderivative.InnerSimplified * gamma - shifted;
}
/// <summary>
/// <c>int P(x) Gamma(n, u) dx</c> for <c>u = a + b x</c> with an offset: with <c>P</c> written
/// in powers of <c>u</c>, each <c>p u^k</c> is <c>p (u^(k + 1) Gamma(n, u) - Gamma(n + k + 1, u))/(b (k + 1))</c>.
/// </summary>
private static Entity? BesideAPolynomial(Entity polynomial, Entity.IncompleteGammaf gamma, Entity slope, Entity offset, Entity.Variable x)
{
// A power (c + d x)^k of a linear, the shape the integrand is usually written in, as
// the binomial it is in u: with s = b c - a d, c + d x is (s + d u)/b, so the weight of
// u^j is C(k, j) s^(k - j) d^j/((j + 1) b^(k + 1)), and the antiderivative vanishing at
// u = 0 is ((c + d x)^(k + 1) - (s/b)^(k + 1))/((k + 1) d).
var (linear, power) = polynomial is Entity.Powf(var written, Entity.Number.Integer exponent) ? (written, exponent.EInteger) : (polynomial, EInteger.One);
if (power.Sign > 0 && power.CompareTo(EInteger.FromInt32(32)) <= 0 && linear.ContainsNode(x)
&& TreeAnalyzer.TryGetPolyLinear(linear, x, out var d, out var c))
{
var k = power.ToInt32Checked();
var s = (slope * c - offset * d).InnerSimplified;
var kPlusOne = Entity.Number.Integer.Create(k + 1);
Entity weighted = Entity.Number.Integer.Zero;
// Without a zeroth power, which is 1 provided its base is not 0.
for (var j = 0; j <= k; j++)
weighted += (Entity.Number.Rational.Create(Binomial(k, j).EInteger, EInteger.FromInt32(j + 1)) * Power(s, k - j) * Power(d, j)).InnerSimplified
* MathS.IncompleteGamma((gamma.Parameter + (j + 1)).InnerSimplified, gamma.LowerLimit);
return (MathS.Pow(linear, kPlusOne) / d - (MathS.Pow(s, kPlusOne) / (d * MathS.Pow(slope, kPlusOne))).InnerSimplified) / kPlusOne * gamma
- weighted / MathS.Pow(slope, kPlusOne);
}
var u = Entity.Variable.CreateUnique(polynomial + gamma + x, "u");
if (ThePowersOf(polynomial.Substitute(x, (u - offset) / slope), u, 32) is not { } inU)
return null;
Entity antiderivative = Entity.Number.Integer.Zero;
Entity shifted = Entity.Number.Integer.Zero;
foreach (var monomial in inU)
{
var next = Entity.Number.Integer.Create(monomial.Key.Add(1));
var weight = (monomial.Value / (next * slope)).InnerSimplified;
antiderivative += weight * Power(gamma.LowerLimit, next.EInteger.ToInt32Checked());
shifted += weight * MathS.IncompleteGamma((gamma.Parameter + next).InnerSimplified, gamma.LowerLimit);
}
return antiderivative * gamma - shifted;
}
private static Entity Power(Entity @base, int power) => power switch
{
0 => Entity.Number.Integer.One,
1 => @base,
_ => MathS.Pow(@base, power)
};
private static Entity Power(Entity @base, Entity power)
=> power is Entity.Number.Integer { EInteger: var whole } && whole.CanFitInInt32() ? Power(@base, whole.ToInt32Checked()) : MathS.Pow(@base, power);
/// <summary>
/// <paramref name="factor"/> read as <c>(d x)^m</c>, with <c>d</c> and <c>m</c> free of
/// <paramref name="x"/>: <c>x</c> itself, a power of it, or a power of a multiple of it.
/// </summary>
private static bool TryReadAPowerOfAMultiple(Entity factor, Entity.Variable x, out Entity @base, out Entity scale, out Entity exponent)
{
@base = x;
scale = exponent = Entity.Number.Integer.One;
if (factor == x)
return true;
if (factor is not Entity.Powf(var written, var power) || power.ContainsNode(x))
return false;
exponent = power;
if (written == x)
return true;
if (!TreeAnalyzer.TryGetPolyLinear(written, x, out var multiple, out var offset) || !TreeAnalyzer.IsZero(offset))
return false;
@base = written;
scale = multiple;
return true;
}
internal static Entity? TryStandardIntegrals(Entity expr, Entity.Variable x) => expr switch
{
// Every rule below divides by the linear rate of its integrand's argument, and
// an argument that mentions x without depending on it has a rate of zero. That
// put a literal division by zero into the answer, so `e ^ (x + -x)` integrated
// to `e ^ (x + -x) / (0 * ln(e))`, which evaluates to NaN. Each of those
// integrands depends on x only through that argument, so a zero rate means the
// integrand is a constant and integrates to itself times x.
//
// The rate has to be decidably zero: a symbolic one, as in sin(a * x), is not,
// and answering sin(a * x) * x there would be wrong for every non-zero a.
//
// Reachable from ordinary input once two powers of one base are gathered:
// e^x * e^(-x) becomes e^(x + -x), whose rate is zero while `x + -x` is still
// written out. https://github.com/asc-community/AngouriMath/issues/785
_ when RateBearingArgument(expr, x) is { } constant
&& TreeAnalyzer.TryGetPolyLinear(constant, x, out var rate, out _)
&& rate.Evaled is Entity.Number.Complex { IsZero: true }
=> expr * x,
Entity.Sinf(var arg) when
TreeAnalyzer.TryGetPolyLinear(arg, x, out var a, out _) =>
-MathS.Cos(arg) / a,
Entity.Cosf(var arg) when
TreeAnalyzer.TryGetPolyLinear(arg, x, out var a, out _) =>
MathS.Sin(arg) / a,
// sin(u)^n * cos(u)^m for whole n and m, which covers sin(x)^2 and cos(x)^2
// as much as sin(x)^3 or sin(x)^2 * cos(x)^2.
_ when TryReadSineCosinePowers(expr, x, out var trigArg, out var sinePower, out var cosinePower)
&& sinePower + cosinePower >= 2
&& TreeAnalyzer.TryGetPolyLinear(trigArg, x, out var trigRate, out _) =>
IntegrateSineCosinePowers(trigArg, sinePower, cosinePower, trigRate, x),
Entity.Secantf(var arg) when
TreeAnalyzer.TryGetPolyLinear(arg, x, out var a, out _) =>
MathS.Hyperbolic.Artanh(MathS.Sin(arg)) / a,
Entity.Cosecantf(var arg) when
TreeAnalyzer.TryGetPolyLinear(arg, x, out var a, out _) =>
AntiderivativeLog(MathS.Tan(0.5 * arg)) / a,
Entity.Tanf(var arg) when
TreeAnalyzer.TryGetPolyLinear(arg, x, out var a, out _) =>
-AntiderivativeLog(MathS.Cos(arg)) / a,
Entity.Cotanf(var arg) when
TreeAnalyzer.TryGetPolyLinear(arg, x, out var a, out _) =>
AntiderivativeLog(MathS.Sin(arg)) / a,
Entity.Logf(var @base, var arg) when
!@base.ContainsNode(x) && TreeAnalyzer.TryGetPolyLinear(arg, x, out var a, out var b) =>
((b / a + x) * MathS.Ln(arg) - x) / MathS.Ln(@base),
Entity.Powf(var @base, var power) when
!@base.ContainsNode(x) && TreeAnalyzer.TryGetPolyLinear(power, x, out var a, out _) =>
MathS.Pow(@base, power) / (a * MathS.Ln(@base)),
// The Gaussian: an exponential of a quadratic is an error function of the square it
// completes. With A u^2 the exponent's square part in u = x + b/(2a), the integral
// of e^(A u^2) is sqrt(pi)/(2 sqrt(-A)) erf(sqrt(-A) u), which differentiates back for
// every A that is not zero, whichever root is taken. Where A is decidably positive it
// is written with erfi and the real root instead, so that e^(x^2) is sqrt(pi)/2 erfi(x)
// rather than an error function of i x. https://github.com/asc-community/AngouriMath/issues/1501
Entity.Powf(var @base, var power) when
!@base.ContainsNode(x) && TreeAnalyzer.TryGetPolyQuadratic(power, x, out var a, out var b, out var c)
&& !TreeAnalyzer.IsZero(a) =>
Gaussian(@base, a, b, c, x),
// And the Gaussian beside an even power of x, to either side of it.
_ when GaussianMoment(expr, x) is { } moment => moment,
// By parts against 1, the way the inverse trigonometric functions are:
// int erf(u) = u erf(u) + e^(-u^2)/sqrt(pi), and the same for the other two.
Entity.Erff(var arg) when
TreeAnalyzer.TryGetPolyLinear(arg, x, out var a, out _) =>
(arg * MathS.Erf(arg) + MathS.Pow(MathS.e, -MathS.Sqr(arg)) / MathS.Sqrt(MathS.pi)) / a,
Entity.Erfcf(var arg) when
TreeAnalyzer.TryGetPolyLinear(arg, x, out var a, out _) =>
(arg * MathS.Erfc(arg) - MathS.Pow(MathS.e, -MathS.Sqr(arg)) / MathS.Sqrt(MathS.pi)) / a,
Entity.Erfif(var arg) when
TreeAnalyzer.TryGetPolyLinear(arg, x, out var a, out _) =>
(arg * MathS.Erfi(arg) - MathS.Pow(MathS.e, MathS.Sqr(arg)) / MathS.Sqrt(MathS.pi)) / a,
// And the exponential, logarithmic, trigonometric and hyperbolic integrals, by parts
// against 1 the same way: each derivative is elementary and cancels the u the
// integrated 1 leaves beside it. int Ei(u) = u Ei(u) - e^u, int li(u) = u li(u) -
// Ei(2 ln u), int Si(u) = u Si(u) + cos(u), int Ci(u) = u Ci(u) - sin(u),
// int Shi(u) = u Shi(u) - cosh(u) and int Chi(u) = u Chi(u) - sinh(u).
// https://github.com/asc-community/AngouriMath/issues/1501
Entity.Eif(var arg) when
TreeAnalyzer.TryGetPolyLinear(arg, x, out var a, out _) =>
(arg * MathS.Ei(arg) - MathS.Pow(MathS.e, arg)) / a,
Entity.Lif(var arg) when
TreeAnalyzer.TryGetPolyLinear(arg, x, out var a, out _) =>
(arg * MathS.Li(arg) - MathS.Ei(2 * MathS.Ln(arg))) / a,
Entity.Sif(var arg) when
TreeAnalyzer.TryGetPolyLinear(arg, x, out var a, out _) =>
(arg * MathS.Si(arg) + MathS.Cos(arg)) / a,
Entity.Cif(var arg) when
TreeAnalyzer.TryGetPolyLinear(arg, x, out var a, out _) =>
(arg * MathS.Ci(arg) - MathS.Sin(arg)) / a,
Entity.Shif(var arg) when
TreeAnalyzer.TryGetPolyLinear(arg, x, out var a, out _) =>
(arg * MathS.Shi(arg) - MathS.Hyperbolic.Cosh(arg)) / a,
Entity.Chif(var arg) when
TreeAnalyzer.TryGetPolyLinear(arg, x, out var a, out _) =>
(arg * MathS.Chi(arg) - MathS.Hyperbolic.Sinh(arg)) / a,
// The polygamma functions, each the derivative of the one before: int psi^(n)(u) =
// psi^(n - 1)(u) for n >= 1, and int psi(u) = ln Gamma(u) = ln((u - 1)!), whose value is
// i pi more where Gamma is negative, a constant on each interval between the poles.
// https://github.com/asc-community/AngouriMath/issues/171
Entity.Polygammaf(Entity.Number.Integer { EInteger: var order }, var arg) when order.Sign > 0 &&
TreeAnalyzer.TryGetPolyLinear(arg, x, out var a, out _) =>
MathS.Polygamma(Entity.Number.Integer.Create(order - 1), arg) / a,
Entity.Polygammaf(Entity.Number.Integer { IsZero: true }, var arg) when
TreeAnalyzer.TryGetPolyLinear(arg, x, out var a, out _) =>
MathS.Ln(MathS.Factorial(arg - 1)) / a,
// The upper incomplete gamma function of a linear, alone or beside a power of x or a
// polynomial. https://github.com/asc-community/AngouriMath/issues/2075
_ when IncompleteGammaBesideAPower(expr, x) is { } gamma => gamma,
// And a power beside an exponential of a power, where that is a gamma function and
// neither elementary nor an error function. https://github.com/asc-community/AngouriMath/issues/2075
_ when APowerBesideAnExponentialOfAPower(expr, x) is { } gammaForm => gammaForm,
// And beside a power of a sine and a cosine, as the exponentials Euler's formula writes them.
// https://github.com/asc-community/AngouriMath/issues/2075
_ when APowerBesideATrigonometricFunction(expr, x) is { } trigonometricGammaForm => trigonometricGammaForm,
Entity.Absf(var arg) when
TreeAnalyzer.TryGetPolyLinear(arg, x, out var a, out _) => // ∫ |ax + b| dx = sgn(ax + b) * (ax + b)^2 / (2a)
MathS.Signum(arg) * MathS.Pow(arg, 2) / (2 * a),
Entity.Signumf(var arg) when
TreeAnalyzer.TryGetPolyLinear(arg, x, out var a, out _) => // ∫ sgn(ax + b) dx = |ax + b| / a
MathS.Abs(arg) / a,
// ∫ ln|ax + b| dx = ((ax + b)/a) * (ln|ax + b| - 1)
Entity.Logf(var @base, Entity.Absf(var arg)) when
@base == MathS.e && TreeAnalyzer.TryGetPolyLinear(arg, x, out var a, out _) =>
(arg / a) * (MathS.Ln(MathS.Abs(arg)) - 1),